简体   繁体   English

使用泛型的数组列表实现,其中列表的最大大小是动态的

[英]Array list implementation using generics where the maximum size of the list is dynamic

I want to ask if someone knows how to fix this. 我想问问是否有人知道如何解决这个问题。 I am getting this message: 我收到此消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Main.add(Main.java:40)  // it is for: myList[actSize++] = object;
    at Main.main(Main.java:127) //it is for: ob.add(str+str1+str2); 

I want to ask if what i am doing is right. 我想问一下我在做什么对吗。 I would like to build a programm that uses generics with the following: methods add,remove,get,contains and size. 我想建立一个使用泛型和以下内容的程序:方法添加,删除,获取,包含和大小。 But when I built the program I found out that the generics cannot create an array, so I used from another post in this site: [How to: generic array creation and used the weak typing (unchecked). 但是,当我构建程序时,我发现泛型无法创建数组,因此我在该站点的另一篇文章中使用了[如何:创建泛型数组并使用了弱类型(未选中)。 So the main theme of this program is someone to type in console his first name last and his phone number and then to put it in array of generics so I could save it into an object and then into a specific position. 因此,该程序的主要主题是有人在控制台中键入他的名字和电话号码,然后将其放入泛型数组中,这样我就可以将其保存到一个对象中,然后保存到特定位置。 After that the program dynamically increases the threshold in order for the user to have a lot of contacts. 之后,程序会动态增加阈值,以使用户拥有很多联系。 Then he wil be told if his contact has been duplicated and it will be removed immediatly. 然后,将告知他是否重复了联系人,并将立即将其删除。 After he will be asked if he want to remove a contract and then the program stats all over, until the user finishes his job(adding contracts). 之后,将询问他是否要删除合同,然后程序状态全部统计,直到用户完成工作(添加合同)为止。

I would be glad to hear some opinions. 我很高兴听到一些意见。

(I am sorry for my English if I am not understandable.) (如果我无法理解我的英语,我感到抱歉。)

import java.util.Arrays;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main < T >
{

    private Object[] myList;
    public static int actSize = 0;

    public Main(int s)
    {
        myList = new Object[s];
    }

    public T Array(int i)
    {
        @SuppressWarnings("unchecked")
        final T t = (T) myList[i];
        return t;
    }

    public void add(T object) //end
    {
        if (myList.length - actSize <= 5)
        {
            myList = Arrays.copyOf(myList, myList.length * 2);
            System.out.println("\nNew length: " + myList.length);
        }

        myList[actSize++] = object;
    }

    public void add(T object, int position) //end
    {
        myList[position++] = object;
    }

    public boolean remove(T object) //end
    {
        if (myList[actSize].equals(object))
        {
            myList[actSize] = myList[actSize - 1];
            return true;
        }
        else
            return false;
    }

    public void remove(int position) //end
    {
        myList[position] = myList[position - 1];
    }

    @SuppressWarnings("unchecked")
    public T get(int index) //end
    {
        if (index < actSize)
        {
            return (T) myList[index];
        }
        else
        {
            throw new ArrayIndexOutOfBoundsException();
        }
    }

    public boolean contains(T object) //end
    {
        if (myList[actSize].equals(object))
        {
            return false;
        }
        else
            myList[actSize] = myList[actSize - 1];

        return true;
    }

    public int size() //end
    {
        return actSize;

    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args)
    {
        @SuppressWarnings("rawtypes")
        Main ob = new Main(actSize);
        String str, str1, str2;

        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));

            while (true)
            {
                System.out.print("Do you want to add a contact? press any key to continue or n to exit :");
                String str5 = br.readLine();

                if ("n".equalsIgnoreCase(str5))
                {
                    System.exit(1);
                }

                System.out.print("Enter your First Name :");
                str = br.readLine();

                System.out.print("Enter your Last Name :");
                str1 = br.readLine();

                System.out.print("Enter your Phone Number :");
                str2 = br.readLine();

                ob.add(str + str1 + str2);
                ob.add(str + str1 + str2, actSize);

                if (ob.contains(str + str1 + str2) == true)
                {
                    System.out.println("The contact you entered is duplicated");
                    ob.remove(ob.contains(str + str1 + str2));
                    System.out.println("The contact has been removed");
                }

                System.out.print("Do you want to add contracts? press y to continue :");
                String str3 = br.readLine();
                System.out.println("You just entered:" + str3);

                if ("y".equalsIgnoreCase(str3))
                {
                    System.out.print("Which contract do you wish to be removed?");
                    String str4 = br.readLine();

                    if (str4.equals(actSize))
                    {
                        ob.remove(actSize);
                        System.out.println("The contact has been deleted.");
                    }
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}

Why not using List<YourGenericType> list = new ArrayList<YourGenericType>(); 为什么不使用List<YourGenericType> list = new ArrayList<YourGenericType>(); now you can call list.size(); list.add(); list.set(); list.get();... 现在您可以调用list.size(); list.add(); list.set(); list.get();... list.size(); list.add(); list.set(); list.get();... list.size(); list.add(); list.set(); list.get();... . list.size(); list.add(); list.set(); list.get();... Also ArrayList have a dynamic size. ArrayList也具有动态大小。

I suggest something like this: delete your Main and change your main method to something like this: 我建议这样的事情:删除您的Main并将main方法更改为以下内容:

import java.util.*;
import java.io.*;

public class Test {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        String str, str1, str2;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    System.in));
            while (true) {

                System.out
                        .print("Do you want to add a contact? press any key to continue or n to exit :");
                String str5 = br.readLine();

                if ("n".equalsIgnoreCase(str5)) {
                    System.exit(1);
                }

                System.out.print("Enter your First Name :");
                str = br.readLine();

                System.out.print("Enter your Last Name :");
                str1 = br.readLine();

                System.out.print("Enter your Phone Number :");
                str2 = br.readLine();

                StringBuilder sb = new StringBuilder();
                sb.append(str + str1 + str2);

                for (int i = 0; i < list.size(); i++) {
                    String s = list.get(i);
                    if (s.equals(sb.toString())) {
                        System.out.println("Duplicate");
                        list.remove(i);
                    }
                }
                list.add(sb.toString());

                System.out
                        .print("Do you want to add contracts? press y to continue :");
                String str3 = br.readLine();
                System.out.println("You just entered:" + str3);

                if ("y".equalsIgnoreCase(str3)) {
                    System.out
                            .print("Which contract do you wish to be removed?");
                    String str4 = br.readLine();

                    int index = Integer.parseInt(str4);
                    if (index < list.size() && index > 0) {
                        list.remove(index);
                    }

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

First, you can use List to store unknown amount of data. 首先,您可以使用List存储未知数量的数据。

For your code: 对于您的代码:

myList[actSize++] = object;

throws exception because myList is initialized with 0 length. 抛出异常,因为myList初始化为0长度。 So you cannot put anything in index 0. 因此,您不能在索引0中放入任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM