Sorting and swapping elements in two ArrayLists (Java) -
i new java...
i have 2 arraylists:
sublist1 sublist2 they have been populated method , when run, lists contain following strings:
sublist1: [amulet, map, stone, sword] sublist2: [bottle, shield, wand] what need able sort both lists sublist1 contains elements smaller elements in sublist2 in terms of alphabetical postion. both list sizes must stay same.
expected output:
sublist1: [amulet, bottle, map, shield] sublist2: [stone, sword, wand] my code far:
collections.sort(sublist1); collections.sort(sublist2); //[amulet, map, stone, sword] //[bottle, shield, wand] (int i1 = 0; i1 < sublist1.size(); i1++) { (int i2 = 0; i2 < sublist2.size(); i2++) { if (sublist1.get(i1).compareto(sublist2.get(i1)) < 0) { // first run: element 0: sublist1 = amulet, sublist2 = bottle string temp = sublist1.get(i1); sublist1.set(i1, sublist2.get(i1)); sublist2.set(i1, sublist1.get(i1)); i indexoutofboundsexception following line:
if (sublist1.get(i1).compareto(sublist2.get(i1)) < 0) any appreciated. thanks.
you complicating task sorting 2 lists separately, , iterating on them. suggest follow approach:
- merge 2 list create
newlist = sublist1 + sublist2 - sort
newlist - get sublist equal length of
sublist2end ofnewlist. - get sublist equal length of
sublist1beginning ofnewlist
working code:
collection<string> sublist1 = arrays.aslist("amulet", "map", "stone", "sword"); collection<string> sublist2 = arrays.aslist("bottle", "shield", "wand"); // merge 2 collection in single list list<string> mergedlist = new arraylist<>(sublist1); mergedlist.addall(sublist2); collections.sort(mergedlist); // assign sublist mergedlist original collection reference sublist1 = mergedlist.sublist(0, sublist1.size()); sublist2 = mergedlist.sublist(sublist1.size(), mergedlist.size()); system.out.println(sublist1); // [amulet, bottle, map, shield] system.out.println(sublist2); // [stone, sword, wand]
Comments
Post a Comment