Can I put data in ArrayList <structure> in the java array?

Asked 2 years ago, Updated 2 years ago, 88 views

First of all, assuming that it's a structure, it' name, its age, The name of the structure is st.

ArrayList [] list= new ArrayList[5];

st s = new st(); s.Name ("name"); s.Age (11); list[0] = new ArrayList();

list[0].add(t);

-Output System.out.println(list[0].get(0).getName);

--> Output: name

I have a list[0] here.I don't know how to put data in get(1). Get(0) goes in when I add list[0]. How do I put the first one? Is there a way to put array 0th index into ArrayList's second index??? What's the way?

java arraylist

2022-09-21 16:18

1 Answers

ArrayList<ST>[] list = new ArrayList[5];

ST s = new ST();
s.name = "Hong Gil-dong";
s.age = 11;

list[0] = new ArrayList();

list[0].add(s);
System.out.println(list[0].get(0).name); //Hong Gil-dong

ST t = new ST();
t.name = "Kim Chul-soo";
t.age = 17;

list[0].add(1, t);
System.out.println(list[0].get(1).name); // Kim Chul-soo

ArrayList API contains a method that allows you to put values in the desired index location.

public void add(int index, E element)

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-int-E-

If you just want to keep putting the data in order regardless of a particular index, If you use list.add(item), it just goes straight in. 0,1,2,3,.. It is stored sequentially in the second index.


2022-09-21 16:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.