简体   繁体   中英

Alphabetically sorting an ArrayList<String> using .compareTo()

An assignment we have to do in school is alphabetically sort two different ArrayList s into a final arraylist that contains both of the lists elements lexicographically

For example...

ArrayList sent1 contains in alphabetical order [., adam, mark]

ArrayList sent2 contains in alphabetical order [., betsy, kyle, william]

ArrayList sent3 must contain all of the elements in both ArrayLists in alphabetical order.

I just can't seem to figure out how to do it. My instructor mentioned using a while loop, but I don't just understand how to code the process. Combining sent1 and sent2 into sent3 and then using Collections.sort(sent3) would make the process so much easier and more compact, but the goal of the lab is to practice the using of compareTo() .

如果已经对每个源列表进行了排序,则只需查看每个列表中的第一个元素,然后将“下”(按字母顺序排列)添加到输出列表中,然后重复即可。

It's pretty simple;

List<String> sent3 = new ArrayList<String>(sent1);
sent3.addAll(sent2);
Collections.sort(sent3, new Comparator<String>() {
    public int compare(String a, String b) {
        return a.compareTo(b); // usage here!
    }
}

What you are looking for is to use 2 iterators and just merge these 2 lists. I'll give you some pseudo code.

ArrayList sent1, sent2, sent3;
int i1, i2;
i1 = i2 = 0;
while (i1 < sent1.length() && i2 < sent2.length())
{
 if (sent1[i2].compareTo(sent2[i1])
 {
   sent3.add(sent1[i2]);
   i2++;
 }else
 {
   sent3.add(sent1[i1]);
   i21+;
 }
}
while(i1 < sent1.length()) sent3.add(sent1[i1++]);
while(i2 < sent2.length()) sent3.add(sent2[i2++]);

Here each time will add to my sent3 the minimum of the first items in sent1 and sent2. And when I get one of this lists empty, I will just append the rest of other elements into the sent3.

I think that you can do this:

copy array1 and array2 to array3; then, sort array3. you don't know how to sort using compareTo() ? Check is java documentation.

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