for循环外部的变量被改变了吗?

时间:2016-03-18 01:28:00

标签: java arrays arraylist

我正在使用Java ArrayList创建数组列表,并使用java.util.ArrayList中提供的方法对其进行编辑。我们的老师让我们做各种事情,比如删除列表中的整数并将它们放在别处。

我们的问题集的最后一步是获取在整个类中编辑过的数组,将其复制到一个新数组(我的新数组的变量是newArrayList),取出所有偶数整数复制新列表的数组列表,然后打印出旧的一个没有偶数整数,新的复制从旧的复制与偶数整数并排。

偶数为整数的旧列表为removed = pics
从旧列表中复制的新列表没有偶数为removed = newpics

的整数

我为ArrayList的大小运行了一个for循环,其中包含一个嵌套的if语句,用于标识偶数变量。在打印出来的结果中,newpics似乎与pics一起失去了偶数整数,当我最后将它们打印出来时,它们甚至都缺失整数。我只希望pics甚至缺少整数,并且newpics似乎在for循环的某处被改变了,即使我甚至没有在for循环中提到它。我有多个人看这个,这是非常令人沮丧的。

这是我的代码:

import java.util.ArrayList;
/**
 * Write a description of class ArrayList here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class ArrayListTester
{

    /**
     * An example of a method - replace this comment with your own
     * 
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y 
     */
    public static void main (String[]args)
    {
        ArrayList <Integer> pics = new ArrayList <Integer>();
        for (int i=0; i<6;i++)
        {
            pics.add(i);
        }
        System.out.println("Original ArrayList" +pics);

        System.out.println("__________________________________");

        int secondlasttoFirst = pics.get(4);
        pics.remove(4);
        pics.add(0,secondlasttoFirst);
        System.out.println("Penultimate moved to front" +pics);

        System.out.println("__________________________________");

        int firsttoLast = pics.get(0);
        pics.remove(0);
        pics.add(5, firsttoLast);
        System.out.println("First moved to end" +pics);

        System.out.println("__________________________________");

        int fronttoBack = pics.get(0);
        int backtoFront = pics.get(5);
        pics.remove(0);
        pics.add(0, backtoFront);
        pics.remove(5);
        pics.add(5, fronttoBack);
        System.out.println("Swapped first and last" +pics);

        System.out.println("__________________________________");

        ArrayList <Integer> newpics = new ArrayList <Integer>();      
        newpics = pics;
        System.out.println("newArrayList" +newpics);

        System.out.println("__________________________________");




        int j=0;
        for (j=0; j<pics.size();j++)
        {

            if (pics.get(j) % 2 ==0)
            {
                pics.remove(j);

            }
        }



        System.out.println("Original with evens removed" +pics);
        System.out.println("__________________________________");
        System.out.println("Original newArrayList" +newpics);

    }
}

3 个答案:

答案 0 :(得分:1)

当你说 $host = "localhost"; $sql_username = "root"; $sql_password = "password"; $sql_db = "tryckstore"; $con = mysqli_connect($host, $sql_username, $sql_password,$sql_db) or die("Error"); if (!mysqli_select_db($con, "tryckstore")) { die("Error selecting databse."); } else { echo "ok"; } 时,你只需创建一个指向同一实际内容的新变量。也许你应该考虑制作一个......克隆?

http://www.java2s.com/Tutorial/Java/0140__Collections/CopyingandCloningListspublicObjectclone.htm

答案 1 :(得分:0)

在java中,当你说something = somethingelse时,你实际上存储了对该对象的引用。也就是说,something将具有与其他内容相同的地址。因此,改变是相同的。

查看这个更简单的示例:

<强>代码:

 public static void main(String[] args) {
        // Make an array
        ArrayList<String> strings = new ArrayList<>();
        // And a copy to it...
        // This is just copy of the address
        ArrayList<String> copy = strings;
        // Add to strings
        strings.add("Hi");
        // Add to copy
        copy.add("my");
        // Add to strings
        strings.add("name");
        // Add to copy
        copy.add("is");
        // Add to strings
        strings.add("bob");

        // No matter which one you print, youll get the same string because they are referncing the same thing
        System.out.println(copy);
        // > [Hi, my, name, is, bob]
        System.out.println(strings);
        // > [Hi, my, name, is, bob]


    }

请注意我是如何交替添加内容的,但两者都以相同的结果结束。

以下是如何进行实际复制的方法:

<强>代码

public static void main(String[] args) {
    // Make an array
    ArrayList<String> strings = new ArrayList<>();
    // Add to strings
    strings.add("Hi");
    // Add to strings
    strings.add("name");
    // Add to strings
    strings.add("bob");
    // Now you want a copy
    ArrayList<String> copy = new ArrayList<>(strings);
    // now changes to copy, are only to copy
    copy.add("change just to copy");

    System.out.println(strings);
    // > [Hi, name, bob]
    System.out.println(copy);
    // > [Hi, name, bob, change just to copy]

}

答案 2 :(得分:0)

您实际上确实在循环中提到了其他列表,因为newpics = pics ...您制作了newpics 参考 pics。换句话说,它们是同一个对象,因此对一个对象的更改会反映在另一个对象中。

如果您不希望发生这种情况,只需更改

即可
ArrayList <Integer> newpics = new ArrayList <Integer>();      
newpics = pics;

到此

ArrayList <Integer> newpics = new ArrayList <Integer>(pics);      

此外,在迭代它时调用list.remove()检查其大小可能会导致一些副作用,如跳过元素。你可以通过使用迭代器来解决这个问题。

Iterator<Integer> iter = pics.iterator();
while(iter.hasNext())
{
    int pic = iter.next();
    if (pic % 2 ==0)
    {
        iter.remove();
    }
}
相关问题