簡體   English   中英

在java中創建列表/對象列表

[英]Creating a List of Lists/Objects in java

我最近才開始學習 Java 並想嘗試創建一個列表列表。 在我在互聯網上遇到的所有示例中,為了將整數列表作為不同元素添加到另一個列表中,創建了不同的列表。

當嘗試使用單個列表但每次在添加它們之前更改它的值時((如下面的代碼所示),我得到以下結果。我嘗試執行另一個類似的代碼,但這次只使用一個對象列表. 在這種情況下,我也得到了類似的結果。

class Persona
{
    int num;
    String name;

    public String toString() 
    { return("ID: "+num+" , Name: "+name); }

    public Persona(int num, String name) {
        this.num = num;
        this.name = name; }

    public void set(int num,String name) {
        this.num = num;
        this.name = name;
    }
}

public class Trials {

    public static void main(String[] args) {
       //CASE 1 : TRYING WITH A LIST OF LISTS
        
        List< List< Integer> > collection = new LinkedList<>();

        List<Integer> triplet = new LinkedList<>();

        triplet.add(1);
        triplet.add(3);
        triplet.add(5);

        collection.add(triplet);
        
        System.out.println(collection);
        triplet.clear();

        triplet.add(30);
        triplet.add(65);
        triplet.add(56);
        collection.add(triplet);

        System.out.println(collection); 

      //CASE 2 : TRYING WITH LIST OF OBJECTS

        Persona p1 = new Persona(2,"Amy");

        List< Persona > people = new LinkedList<>();

        people.add(p1);
        System.out.println(people);

        p1.set(4, "Jake");

        people.add(p1);
        System.out.println(people);

      /*OUTPUT:-
      [[1, 3, 5]]
      [[30, 65, 56], [30, 65, 56]]
      [ID: 2 , Name: Amy]
      [ID: 4 , Name: Jake, ID: 4 , Name: Jake]
      */

    }

}

這是否意味着在將對象作為列表元素處理時,它會引用它們? 而且,是否有任何方法可以使代碼與相同的對象/列表一起工作以提供如下所需的輸出?

[[1, 3, 5], [30, 65, 56]] [ID: 2 , Name: Amy, ID: 4 , Name: Jake]

看起來您想要一個包含兩個不同元素的 List,但在每種情況下只創建一個。

List< Persona > people = new LinkedList<>();

// Create p1 (Amy)
Persona p1 = new Persona(2, "Amy");

// Add p1 (Amy) to people, now people is [p1 (Amy)]
people.add(p1);

// [p1 (Amy)]
System.out.println(people);

// Set p1's name to Jake, it also updates in the list because it is the same object
// so now people is [p1 (Jake)]
p1.set(4, "Jake");

// Add p1 to list one more time, now people is [p1 (Jake), p1 (Jake)]
people.add(p1);

// [p1 (Jake), p1 (Jake)]
System.out.println(people);

您可能想要做的是將對象修改p1.set(4, "Jake")替換為對象創建p1 = new Person(4, "Jake") ,然后您就可以開始了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM