简体   繁体   中英

Printing Single Item from ArrayList Created in Another Generic Class?

Trying to get an understanding of generics in Java. I've created an ArrayList using non-generic methods and casting to print them out, everything works fine using the usual array.get(index) but when I use generics to create the list, the get method doesn't work. I can print the whole list just fine, but I want to pick out individual elements. I've tried a few different things which have made the code a little messy probably, so sorry about that. I know things could probably be done an easier way, I'm just trying to learn about Generics in Java and I ran into this issue. I've watched several different videos and found several examples, so I may be trying to put two concepts together the incorrect way. Tried researching, can't find the answer.

First class Generic.java is to create the generic ArrayList.

import java.util.ArrayList;
import java.util.List;

public class Generic<T> {

private ArrayList<T> data;

    public Generic() {
        data = new ArrayList<T>();
    }

    public void add(T element){
        data.add(element);
    }

    //Not even sure if I need these get/set but I put them in there for testing
    public ArrayList<T> getData() {return data;}

    public void setData(ArrayList<T> data) {this.data = data;}

    public String toString(){
        return data.toString();
    }
}

Second class is the main test class:

import java.util.ArrayList;
import java.util.List;


public class Test {

    public static void main(String[] args) {

        List nonGenericList = new ArrayList();
        nonGenericList.add("Enzo");
        nonGenericList.add(458);
        String nonGen1 = (String) nonGenericList.get(0);
        Integer nonGen2 = (Integer) nonGenericList.get(1);

        System.out.println(nonGen1);
        System.out.println(nonGen2);


        Generic<Object> genericList = new Generic<>();
        genericList.add("Enzo");
        genericList.add(458);

        //This is where the .get(0) isn't working for me
        System.out.println(genericList.get(0));
    }
}

Thanks for any help!

Your Generic<T> class doesn't have the method get(int index) , you should create the method if you want to call it...

Try adding this to your Generic<T> class

public T get(int index){
    return data.get(index);
}

您可以在泛型类中定义以下get方法:

   public T get(int i) {return data.get(i);}

You do not have add method you have defined the getData() method, so write

ArrayList a=genericList.getData();
System.out.println(a.get(0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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