简体   繁体   中英

How do I store an array into an element of ArrayList?

Robentry [] Rb = new Robentry[robNum];

How can I store Rb into an ArrayList<E> Rt , so that Rt.get(0) == Rb is true . I do not know how to define E in the ArrayList<E> .

Edit:

If I use :

Robentry [] Rb = new Robentry[robNum];
List<Robentry []> Rt = new  ArrayList<Robentry []>();
// initialize Rb
//...
// 
Rt.add(Rb);

If I change Rb[0] , Rt.get(0)[0] is also changed. So how can I store the content of Rb into Rt so that Rt is independent of Rb ?

ArrayList<Robentry[]> arrList sounds like what you want.

This means arrList is a List (or ArrayList ) of Robentry[] .

you can use Type Robentry[] to a List. like -

List<Robentry []> list = new ArrayList<Robentry []>();

You can declare and use the List of type Robentry[] as below:

    //Declare a list of type Robentry[] 
    List<Robentry[]> list = new ArrayList<Robentry []>();
    //add the rb to the list
    list.add(Rb);

    //compare the list element with Rb
    System.out.println(list.get(0)==Rb);//should print true

Please note: == is fine in above example since list element is same as Rb, otherwise equals method is recommended.

 ArrayList<Robentry> Rt=(ArrayList<Robentry>) Arrays.asList(Rb);

or in your ways,

ArrayList<Robentry[]> Rt=new ArrayList<Robentry[]>();
rt.add(Rb);

This is called Generics,was made to ensure that the variable should contain only specific types.See this for official docs .

Based on your modified question, you probably want

Rt.add(Rb.clone());

or

Rt.add(Arrays.copyOf(Rb, Rb.length));

Array references are passed around by value, so you have to do an explicit copy if you want the arrays to be independent of one another.

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