jeudi 25 mai 2017

Java TreeMap with random seed do not have a fixed size

I want to use this to generate 10 Udisk instances with random price and capacity.

// test.java
import java.util.*;

class Udisk {
    float price;
    int capacity;
    Udisk(float p, int c) {
        this.price = p;
        this.capacity = c;
    }
    @Override
    public String toString() {
        return "Udisk price: "+this.price+" capacity: "+this.capacity;
    }
}

class Main {
    public static void main(String[] args) {
        Map<Float, Udisk> tm = new TreeMap<Float, Udisk>();
        for(int count=0; count < 10; count++) {
            Random rand = new Random(System.currentTimeMillis());
            float price = Math.abs(rand.nextInt())%100;
            int capacity = Math.abs(rand.nextInt())%10;
            Udisk u = new Udisk(price, capacity);
            tm.put(u.price, u);
        }
        System.out.println(tm+ " "+tm.size());
    }
}

After javac test.java, I ranjava Main for several times, and the result is so strange

First Time: {3.0=Udisk price: 3.0 capacity: 1} 1
Second Time: {33.0=Udisk price: 33.0 capacity: 8, 86.0=Udisk price: 86.0 capacity: 0} 2
Third Time: {46.0=Udisk price: 46.0 capacity: 8} 1
Fourth Time: {24.0=Udisk price: 24.0 capacity: 1, 73.0=Udisk price: 73.0 capacity: 5} 2

All these results has less than 10 items in the TreeMap. After changing the code to

import java.util.*;

class Udisk {
    float price;
    int capacity;
    Udisk(float p, int c) {
        this.price = p;
        this.capacity = c;
    }
    @Override
    public String toString() {
        return "Udisk price: "+this.price+" capacity: "+this.capacity;
    }
}

class Main {
    public static void main(String[] args) {
        Map<Float, Udisk> tm = new TreeMap<Float, Udisk>();
        for(int count=0; count < 10; count++) {
            Random rand = new Random(System.currentTimeMillis());
            float price = Math.abs(count)%100;
            int capacity = Math.abs(count)%10;
            Udisk u = new Udisk(price, capacity);
            tm.put(u.price, u);
        }
        System.out.println(tm+ " "+tm.size());
    }
} 

The answer is correct

{0.0=Udisk price: 0.0 capacity: 0, 1.0=Udisk price: 1.0 capacity: 1, 
2.0=Udisk price: 2.0 capacity: 2, 3.0=Udisk price: 3.0 capacity: 3, 
4.0=Udisk price: 4.0 capacity: 4, 5.0=Udisk price: 5.0 capacity: 5, 
6.0=Udisk price: 6.0 capacity: 6, 7.0=Udisk price: 7.0 capacity: 7, 
8.0=Udisk price: 8.0 capacity: 8, 9.0=Udisk price: 9.0 capacity: 9} 10

I wonder what did I missed in Random that caused the former problem, thanks for helping!




Aucun commentaire:

Enregistrer un commentaire