Зависит от того, где объявлены список и список2 . Я бы предложил предоставить String Array (list) и List List (list2) в качестве аргументов для метода nextItem () , а также значение начального индекса в качестве третьего аргумента, например:
public static int nextItem(String[] stringArray, List<String> listInterface, int startIndex) {
int index = -1;
for (int i = startIndex; i < stringArray.length; i++) {
if (!listInterface.contains(stringArray[i])) {
return i;
}
}
return -1;
}
Приведенный выше пример метода nextItem () возвращает целочисленное значение, которое будет значением индекса, при котором элемент в массиве строк (список) также не содержится в коллекции интерфейса интерфейса (list2) ). Ваш естественный первый вызов этого метода предоставит 0 в качестве аргумента для параметра startIndex . Чтобы получить следующий элемент , а не , общий для обоих списков и list2 , необходимо указать вернул значение индекса из предыдущего nextItem () , добавьте 1 и предоставьте его как startIndex к следующему nextItem () вызов метода. Вот пример:
String[] list = {"apple", "banana", "cherry", "donut", "egg", "fish", "grape"};
List<String> list2 = new ArrayList<>( Arrays.asList("apple", "cherry", "donut", "fish"));
int idx = 0;
while (idx != -1) {
idx = nextItem(list, list2, idx);
if (idx != -1) {
System.out.println(list[idx]);
idx++;
}
}
В окне консоли будет отображаться:
banana
egg
grape
В следующем примере кода не используется al oop, и он приведен здесь, чтобы быть, возможно, более наглядным помощь тому, что делает код:
String[] list = {"apple", "banana", "cherry", "donut", "egg", "fish", "grape"};
List<String> list2 = new ArrayList<>( Arrays.asList("apple", "cherry", "donut", "fish"));
String noMore = "** There are no more non-shared items in the lists! **";
// Get first non-shared item
int idx = nextItem(list, list2, 0);
if (idx > -1) {
System.out.println(list[idx]);
}
else {
System.out.println("Both lists contain all the same items");
// return from method or event
}
// Get second non-shared item
idx = nextItem(list, list2, idx + 1);
if (idx > -1) {
System.out.println(list[idx]);
}
else {
System.out.println(noMore);
// return from method or event
}
// Get third non-shared item
idx = nextItem(list, list2, idx + 1);
if (idx > -1) {
System.out.println(list[idx]);
}
else {
System.out.println(noMore);
// return from method or event
}
// Get fourth non-shared item (if any)
idx = nextItem(list, list2, idx + 1);
if (idx > -1) {
System.out.println(list[idx]);
}
else {
System.out.println(noMore);
// return from method or event
}
В окне консоли будет отображаться:
banana
egg
grape
** There are no more non-shared items in the lists! **