public class HashHistogram {
static String[] words = {"Man", "skall", "läsa", "javadoc", "innan", "java", "installeras"};
public static void main(String[] args) {
int[] histogram = new int[5];
for (String w1: words) {
for (String w2: words) {
int hashSum = w1.hashCode() + w2.hashCode();
histogram[hashSum % histogram.length] ++;
}
}
System.out.print(Arrays.toString(histogram));
}
}
- Kompilerar inte
- Evig loop
- Skriver ut histogrammet
- Något annat
Ok, det fungerade inte. Ah, om hashCode är negativt så blir resultatet negativt. Då gör vi det positivt.
public class HashHistogram {
static String[] words = {"Man", "skall", "läsa", "javadoc", "innan", "java", "installeras"};
public static void main(String[] args) {
int[] histogram = new int[5];
for (String w1: words) {
for (String w2: words) {
int hashSum = w1.hashCode() + w2.hashCode();
histogram[Math.abs(hashSum) % histogram.length] ++;
}
}
System.out.print(Arrays.toString(histogram));
}
}
- Kompilerar inte
- Evig loop
- Skriver ut histogrammet
- Något annat
Two component: Integer.MIN_VALUE 10000000 00000000 00000000 00000000 Invert 01111111 11111111 11111111 11111111 Add 1 10000000 00000000 00000000 00000000
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
public class UrlEquals {
static final String[] ADDRESSES = {
"http://google.com",
"http://lindsjo.net",
"http://google.com",
"http://tilialacus.net",
"http://google.com",
};
public static void main(String...args) throws Exception {
java.security.Security.setProperty("networkaddress.cache.ttl" , "0");
Set<URL> set = new HashSet<URL>();
for (String address: ADDRESSES) {
set.add(new URL(address));
}
for (URL url: set) {
System.out.println(url);
}
}
}
The following code does not work since min + max overflows. Run with -Xmx1200m
public class AverageInt {
public static void main(String[] args) {
byte[] data = new byte[Integer.MAX_VALUE / 2 + 10];
System.err.format("Allocated %s elements, %s bytes (%.2fGB)", data.length, data.length, data.length/1024d/1024/1024);
data[data.length - 1] = Byte.MAX_VALUE;
find (data, Byte.MAX_VALUE);
}
private static void find(byte[] data, byte value) {
int min = 0;
int max = data.length - 1;
int middle = (min + max) / 2;
while (data[middle] != value && min != max) {
if (data[middle] < value) {
min = middle;
} else {
max = middle;
}
middle = (min + max) / 2;
}
System.err.println(min + " " + max + " " + middle);
}
}