Как десериализовать файл? - PullRequest
0 голосов
/ 28 апреля 2018

Мне нужна помощь с № 3 и № 5.

  1. Создайте коллекцию и заполните ее 20 случайными числами от 1 до 15 (включительно)

    List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1)
       ));
    
  2. Распечатать цифры

    System.out.println(list1);
    
  3. Заполнить конструктор класса Random значением 13.

    • что значит посеять ctor?
  4. Сериализация коллекции в файл с именем Numbers.ser

    try (ObjectOutputStream serialize = new ObjectOutputStream(new FileOutputStream("src/serialize/Numbers.ser"))) {
        serialize.writeObject(list1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  5. Десериализовать файл в новую коллекцию с именем numberFromFile. Удалить все повторяющиеся номера

    • Здесь я запутался в том, как десериализовать. Какое объяснение?

Ответы [ 2 ]

0 голосов
/ 28 апреля 2018
//Seed the constructor of class Random with the value 13.
Random rand = new Random(13);

//Create a collection and fill it with 20 random numbers between 1 and 15 (inclusive)

List<Integer> list1 = new ArrayList<>();

for (int i = 0; i < 20; i++) {
    list1.add(rand.nextInt(15) + 1);  // Note here
}

//Print the numbers

System.out.println(list1);

//Serialize the collection to a file called Numbers.ser

try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("Numbers.ser"))) {
    out.writeObject(list1);
} catch (IOException e) {
    e.printStackTrace();
}

//Deserialize the file into a new collection called numberFromFile. Remove all duplicate numbers
//this is where I am confused on how to deserialize. Can you someone explain this to me?
List<Integer> numberFromFile = null;
try (ObjectInputStream in = new ObjectInputStream(
        new FileInputStream("Numbers.ser"))) {
    numberFromFile = (List<Integer>) in.readObject();
} catch (Exception e) {
    e.printStackTrace();
}

//System.out.println(numberFromFile);

Set<Integer> distinct = new HashSet<>(numberFromFile); 
System.out.println(distinct);
0 голосов
/ 28 апреля 2018

Инициализация Random начальным значением означает, что он снова сгенерирует ту же последовательность случайных чисел. Просто проверьте документы: https://docs.oracle.com/javase/8/docs/api/java/util/Random.html

Для чтения отдельных чисел из вашего файла вы можете сделать что-то вроде:

try(ObjectInputStream deserialize = new ObjectInputStream(new FileInputStream("src/serialize/Numbers.ser"))) {
    List<Integer> list2 = (List<Integer>) deserialize.readObject();
    System.out.println(list2.stream().distinct().collect(Collectors.toList()));
} catch(...) { ... }
...