如何使用数组列表仅保存在文本列表中多次出现的数字的第一次出现?

时间:2015-11-11 02:44:38

标签: java arraylist

我是java的初学者,所以请放轻松。我正在尝试读取文件,并将文件中出现的第一次出现的重复数字保存到ArrayList中。

这是我到目前为止所做的:

import java.io.*;
import java.util.Scanner;

public class ListReader
{
  File numbers = new File("numbers.txt");
  //numbers.txt has numbers {26, 26, 44, 9, 64, 7, 19, 11, 80, 9}
  Scanner in = new Scanner(numbers);
  ArrayList<Integer> nums = new ArrayList<Integer>();
  while(in.hasNextInt())
  {
     nums.add(in.nextInt());
  } 
  int j = nums.size() - 2;
  for(int i = nums.size() - 1; i >= 0; i--)
  {
     if(nums.get(i) == nums.get(j))
     {
       nums.remove(nums.get(i)));
       j--;
     }
     else
     {
       j--;
     }
  }
  System.out.println(nums);
}

每次运行代码时,我都会得到索引超出范围的错误,我不知道如何避免。如果纠正了越界错误,这是否会成功摆脱额外的26和9?

2 个答案:

答案 0 :(得分:1)

使用Set。我相信您希望保留广告订单顺序,因此请使用LinkedHashSet(如果您希望使用TreeSet进行排序)。像,

Integer[] arr = { 26, 26, 44, 9, 64, 7, 19, 11, 80, 9 };
List<Integer> nums = Arrays.asList(arr); // <-- to simplify 
Set<Integer> set = new LinkedHashSet<>(nums);
System.out.println(set);

输出

[26, 44, 9, 64, 7, 19, 11, 80]

答案 1 :(得分:1)

使用set是一种更容易的方法,但是,如果需要使用列表,请尝试:

public class ListReader {
//numbers.txt has numbers {26, 26, 44, 9, 64, 7, 19, 11, 80, 9}
ArrayList<Integer> nums = new ArrayList<>();
//I will manually put items into list, just to evade creating a file
//You keep doing your thing :)
void addItems() {
    nums.add(26);
    nums.add(26);
    nums.add(44);
    nums.add(9);
    nums.add(64);
    nums.add(7);
    nums.add(19);
    nums.add(11);
    nums.add(80);
    nums.add(9);
}
void removeExtraItems() {
    //Creating a list with extraItems that will be removed further
    ArrayList<Integer> extraItems = new ArrayList<>();
    //Whenever a copy is found from num arrayList - this list gets that copy
    ArrayList<Integer> numsCopy = new ArrayList<>();
    for (int i = 0; i < nums.size(); i++) {
        if(numsCopy.contains(nums.get(i))) {
            extraItems.add(nums.get(i));
        }
        else{numsCopy.add(nums.get(i));
        }
    }
    //for each extraItem, you check the num list backwards - if it finds it , it removes it and break;
    //if you go nums.remove(extraItems.get(i)
    //it will remove the first occurence
    //i guess that you dont want that
    for (int i = 0; i < extraItems.size(); i++) {
        for (int j = nums.size()-1; j >= 0; j--) {
            if(nums.get(j).equals(extraItems.get(i))){
                nums.remove(extraItems.get(i));
                break;
            }
        }
    }
}
//prints list
void printList() {
    for (int i = 0; i < nums.size(); i++) {
        System.out.println(nums.get(i));
    }
}
public static void main(String[] args) {
    ListReader lr = new ListReader();
    lr.addItems();
    lr.removeExtraItems();
    lr.printList();
}

}