简体   繁体   English

如何将数据输入到用户定义类的arraylist中?

[英]how to input data into an arraylist for user defined class?

for(i=0;i<in.length;i++)
    {
        for(j=i+1;j<in.length;j++)
        {
            //System.out.println("for"+in[i].val);
            //System.out.println("for "+in[j].val);
            if(comp(in[i].bin,in[j].bin,n)!=null)
            {
                String bi=comp(in[i].bin,in[j].bin,n);
                //System.out.println("is it null "+co[k]);
                coin.a(in[i],in[j],bi);//taken input
                co.add(coin);//now passing to array list HERE LIES THE PROBLEM!!!
                System.out.println(in[i].val+","+in[j].val+"="+coin.bin);
                in[i].combo=true;
                in[j].combo=true;
                k++;
            }   

        }
    }

55f96302address of coin 55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302address of coin @55f96302 55f96302硬币地址55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55f96302硬币地址@ 55f96302 55

As you can see the reference of all elements in the list is same as that of "coin" what should i do to solve this? 如您所见,列表中所有元素的引用与“硬币”的引用相同,我应该怎么做才能解决此问题?

I guess you wouldn't have any issue having a references build over a collection of couple class. 我想您在夫妇类集合上建立引用不会有任何问题。 This is the right way on dealing with elements storage in java. 这是处理Java中元素存储的正确方法。

If I understand the question correctly, your problem is that you do not want the item stored in the list to be the same element as the one stored in your variable coin . 如果我对问题的理解正确,那么您的问题是您不希望列表中存储的项目与可变coin存储的项目相同。 In this case, you should create an exact copy of the object stored in the variable coin and put the copy into the list. 在这种情况下,您应该创建存储在变量coin中的对象的精确副本,并将副本放入列表中。

In fact, you should always be careful when passing around mutable objects, eg, putting them into a list. 实际上,在传递可变对象时,例如将它们放入列表中时,应始终小心。 Otherwise, your program can become hard to debug. 否则,您的程序可能会变得难以调试。 Search for defensive copy in Java . 在Java中搜索防御性副本

I can think of two ways of creating a defensive copy: cloning and copy constructor . 我可以想到两种创建防御性副本的方法: 克隆副本构造函数 However, note that . 但是,请注意。 implementing Cloneable is not trivial . 实现Cloneable并非易事

Also, I would suggest you to think about whether and how you can make your class couple immutable. 另外,我建议您考虑是否以及如何使班级couple一成不变。 In most cases, the advantages of having an immutable class (ie, not having to worry about defensive copying) outweight the disadvanteges (ie, creating new objects, leading to a bit of a higher cost in memory and CPU cycles). 在大多数情况下,拥有不可变的类(即不必担心防御性复制)的优点会超过缺点(即创建新的对象,从而导致内存和CPU周期的成本更高)。

TL;DR: The only reason to not pass the same reference into the arraylist is that the item could potentially be modified by everyone that has access to it. TL; DR:不将相同引用传递到arraylist的唯一原因是,有权访问该条目的每个人都可能修改该条目。 Create a defensive copy or make your object immutable. 创建防御性副本或使您的对象不可变。

Edit: After you have updated your example, I see your problem (at least I think I do). 编辑:更新示例后,我看到了您的问题(至少我认为是这样)。 I tried to reconstruct your example as a minimum working example. 我试图将您的示例重构为最低限度的工作示例。 What you essentially have is: 您基本上拥有的是:

public class Coin {

    int value;

    public Coin(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public static void main(String[] args) {
        Coin myCoin = new Coin(0);
        List<Coin> bankAccount = new ArrayList<Coin>();
        for (int coinValue = 0; coinValue < 5; coinValue ++) {
            myCoin.setValue(coinValue);
            bankAccount.add(myCoin);
        }
        for(Coin coin : bankAccount)
            System.out.println(coin);
    }

    @Override
    public String toString() {
        return "Coin: " + value;
    }

}

If you run this code, then all coins in the list will have value 4. The reason is, that the method setValue (which corresponds to your method a ) mutates the Coin instance. 如果运行此代码,则列表中的所有硬币都将具有值4。其原因是,方法setValue (对应于您的方法a )使Coin实例发生了突变。 The best way to solve this (if possible) is to make Coin immutable and return a new Coin instance when calling setValue . 解决此问题的最佳方法(如果可能)是使Coin不可变,并在调用setValue时返回一个新的Coin实例。 The code would look like this: 代码如下所示:

public class ImmutableCoin {

    final int value;

    public ImmutableCoin(int value) {
        this.value = value;
    }

    public ImmutableCoin setValue(int value) {
        return new ImmutableCoin(value);
    }

    public static void main(String[] args) {
        ImmutableCoin myCoin = new ImmutableCoin(0);
        List<ImmutableCoin> bankAccount = new ArrayList<ImmutableCoin>();
        for (int coinValue = 0; coinValue < 5; coinValue ++) {
            myCoin = myCoin.setValue(coinValue);
            bankAccount.add(myCoin);
        }
        for(ImmutableCoin coin : bankAccount)
            System.out.println(coin);
    }

    @Override
    public String toString() {
        return "ImmutableCoin: " + value;
    }

}

Try running this code. 尝试运行此代码。 You will now not have the same object inserted multiple times in your list. 现在,您将不会在列表中多次插入同一对象。

If however, your method a must modify the object and is not allowed to return a new object, then you must make a copy of the object yourself in the loop, modify this copy, and then insert the copy. 但是,如果方法a 必须修改对象并且不允许返回新对象,则必须在循环中自己创建对象的副本,修改此副本,然后插入副本。 The code could look something like this: 代码看起来像这样:

public class MutableCoin {

    int value;

    public MutableCoin(int value) {
        this.value = value;
    }

    // copy constructor
    public MutableCoin(MutableCoin toCopyFrom) {
        this.value = toCopyFrom.value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public static void main(String[] args) {
        MutableCoin myCoin = new MutableCoin(0);
        List<MutableCoin> bankAccount = new ArrayList<MutableCoin>();
        for (int coinValue = 0; coinValue < 5; coinValue ++) {
            // make a copy
            myCoin = new MutableCoin(myCoin);
            myCoin.setValue(coinValue);
            bankAccount.add(myCoin);
        }
        for(MutableCoin coin : bankAccount)
            System.out.println(coin);
    }

    @Override
    public String toString() {
        return "MutableCoin: " + value;
    }

}

This will also work. 这也将起作用。 I hope this helps. 我希望这有帮助。

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

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