简体   繁体   中英

two dimensional arraylists and input/sorting

I am trying to add all the doubles between two <end> instances into an arraylist within an arraylist (at each index of <end> have the doubles between the <end> s, and so forth)

ArrayList<ArrayList<Double>> myArr = new ArrayList<ArrayList<Double>>();
int j = 0;
int nLine = 0;

    while(scan.hasNext()) {
        String line = scan.next();

        //System.out.println(line);
        if(!line.equals("<end>")) {
            nLine = Double.valueOf(line);
            ArrayList<Double> row = new ArrayList<Double>();
            myArr.add(row);


            row.add(j, nLine);
            j=j++;

        } else {
            j=j++;
        }
    }

As it stands now the code is putting in a single double in a an array (as opposed to all of the ones between statements; thus the output looks like this: [[1.4], [3], [15], [3.2], etc. etc.

where I want it to look like this: [[1.4, 3, 15, 3.2], [5, 13.4], [954.3, etc....

The file it is scanning is essentially:

<end>
1.4
3
15
3.2
<end>
5
13.4
<end>
954.3
43 etc. etc. (infinitely)

My goal (eventually) is to tally how many doubles are in each arrayList index and make sure none of the doubles are exactly the same, and to make sure each of the row arrays have no more than 10 values in them. So I have been stuck and any help is appreciated.

Thanks for any help.

ArrayList<ArrayList<Double>> myArr = new ArrayList<ArrayList<Double>>();
int nLine = 0;

ArrayList<Double> currArr = null;

while(scan.hasNext()) {
    String line = scan.next();

    if(!line.equals("<end>")) {
        nLine = Integer.valueOf(line);

        currArr.add(nLine);
    } else {
        if(currArr!=null) myArr.add(currArr);

        currArr = new ArrayList<Double>();
    }
}

if(currArr!=null) myArr.add(currArr);

In the middle of the code you're using Integer instead of Double . Not sure why so I left it. Code assumes the input always starts with <end> .

You could use a HashSet as a way to keep track of the duplicates (or better yet use an ArrayList of Sets instead to avoid the extra data structure)

Here's an example of generating a random # of ArrayLists without dups:

ArrayList<ArrayList<Integer>> myArr = new ArrayList<ArrayList<Integer>>();      
HashSet<Integer> duplicates = new HashSet<Integer>();
Random random = new Random();

for(int x=0; x<3; x++) {
    ArrayList<Integer> row = new ArrayList<Integer>();
    myArr.add(row);
    for(int y=0; y<3; y++) {
        int randomInt = random.nextInt(100);
        if(!duplicates.contains(randomInt)) {
            row.add(0,randomInt);
            duplicates.add(randomInt);
        }
    }
}

for(int i=0;i<myArr.size();i++)
{
    System.out.println(myArr.get(i));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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