0

我为长标题道歉,如果您能想到更好的标题,请告诉我!

我正在做的是尝试创建一个 ArrayList 的 ArrayList 并将 ArrayLists 一一添加到其中。我拥有的两个AL<AL<I>>s 被称为三角形和正方形,我AL<I>s通过 addToList() 方法添加 - 将AL<I>调用的 temp 添加到适当的AL<AL<I>>. temp 似乎没有问题,但是在我运行整个方法 figurateNumbers() 之后,我AL<AL<I>>s只包含 [98,70],这是要添加的最后一个 temp。代码如下:

import java.util.ArrayList;
import java.util.Iterator;

    public class problem
    {
        public static ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>();
        public static ArrayList<ArrayList<Integer>> square = new ArrayList<ArrayList<Integer>>();
        public static ArrayList<Integer> temp = new ArrayList<Integer>();

        public static void figurateNumbers() 
        //Inserts into individual arraylists, numbers, all figurate numbers square : octagonal
        {
            for (int ii = 1; ii < 141; ii++) 
            {
                if ((ii * ii >= 1000) & (ii * ii < 10000))
                    addToList(ii * ii , square);
                if (((ii * ii + ii) / 2 >= 1000) & ((ii * ii + ii) / 2 < 10000))
                    addToList((ii * ii + ii) / 2 , triangle);
            }
}


    public static void addToList(int num, ArrayList<ArrayList<Integer>> list)
    //Splits the two parts of the number and inserts the arraylist into the proper arraylist
    {
        temp.clear();
        int numInt_one = Integer.parseInt(String.valueOf(num).substring(0,2));  
        int numInt_two = Integer.parseInt(String.valueOf(num).substring(2,4));  
        temp.add(numInt_one);
        temp.add(numInt_two);
        list.add(temp);
    }

    public static void main (String [] args) 
    {
        figurateNumbers();

        System.out.println(triangle.size());
        System.out.println(square.size());
    Iterator<ArrayList<Integer>> it = square.iterator();
    while(it.hasNext())
    {
        ArrayList<Integer> obj = it.next();
        System.out.println(obj);
    }
        System.out.println(triangle.get(25));
        }
}

任何帮助将不胜感激,无论是关于手头的问题还是我对这些数据结构的使用。

4

2 回答 2

5

您不是每次在下面调用时都创建一个新的 temp 实例,而是将相同的列表添加到您正在清除的列表中。记住它是添加的列表的引用。

 public static void addToList(int num, ArrayList<ArrayList<Integer>> list)
    //Splits the two parts of the number and inserts the arraylist into the proper arraylist
    {
      //  temp.clear();// this is the issue do below
        ArrayList<Integer> temp = new ArrayList<Integer>();
        int numInt_one = Integer.parseInt(String.valueOf(num).substring(0,2));  
        int numInt_two = Integer.parseInt(String.valueOf(num).substring(2,4));  
        temp.add(numInt_one);
        temp.add(numInt_two);
        list.add(temp);
    }
于 2013-10-03T14:41:19.097 回答
2

您正在重用相同的温度。不要 clear() 它,每次在 addToList() 中创建一个新的(并使用局部变量来清楚)。

此外,在 addToList 中,除以 100 或取模(哎呀,1000?不回 100)比所有字符串操作更容易。例如

int numInt_one = num / 100;
int numInt_two = num % 100;

最后一个小建议:在您的 figurateNumbers() 循环中,您不能从 34 开始 ii 吗?虽然速度提升可能不值得付出努力,但我内心的数学家想要这样做。:-)

于 2013-10-03T14:41:49.613 回答