我为长标题道歉,如果你能想到更好的标题,请告诉我!
我正在做的是尝试创建ArrayLists的ArrayList并逐个添加ArrayLists.AL<AL<I>>我拥有的两个被称为三角形和正方形,我AL<I>s通过addToList()方法添加 - 将被AL<I>调用的temp 添加到适当的AL<AL<I>>.temp似乎没有问题,但是在我运行整个方法figurateNumbers()之后,我AL<AL<I>>s只包含[98,70],这是要添加的最后一个临时值.代码如下:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
无论是关于手头的问题还是我对这些数据结构的使用,都会非常感谢任何帮助.
每次在下面调用时,您都不会创建一个新的临时实例,相同的列表将添加到列表中,您要清除它.记住它是添加的列表的引用.
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5586 次 |
| 最近记录: |