我有一个点类,有XY坐标和点的索引,我用索引作为键,点对象作为值添加到HashMap中,问题在程序中,谢谢各位!!!
import java.util.*;class Point {
double x;
double y;
int index;
public Point(double x, double y, int index) {
this.x = x;
this.y = y;
this.index = index;
}
}class Test {
private static final int N = 20;
public static void main(String[] args) {
HashMap pointMap = new HashMap();
Point[] pointSet1 = new Point[N];
Point[] pointSet2 = new Point[N];
for (int i = 0; i < N; i++) {
// pointSet1[i] = new Point(100 * Math.random(), 100 * Math.random(),
// i * i + 10);
Point p = new Point(100 * Math.random(), 100 * Math.random(),i * i + 10);
pointMap.put(new Integer(p.index), p);
pointSet1[i] = p;
}/*
问题:1.pointMap中的顺序是否和pointSet1的顺序是一样的?不一样的话怎样保证是按顺序添 加进去的,这个顺序对我的程序很重要而且要用到HashMap这种数据结构或类似的,即有键/值。有没有别的方法或数据结构可以实现呢??
2.怎样将pointMap中的所有value放到pointSet2中???
最好能帮我把代码写出来,本人初学,很多东西不懂,谢谢各位了:)
*/ }
}
import java.util.*;class Point {
double x;
double y;
int index;
public Point(double x, double y, int index) {
this.x = x;
this.y = y;
this.index = index;
}
}class Test {
private static final int N = 20;
public static void main(String[] args) {
HashMap pointMap = new HashMap();
Point[] pointSet1 = new Point[N];
Point[] pointSet2 = new Point[N];
for (int i = 0; i < N; i++) {
// pointSet1[i] = new Point(100 * Math.random(), 100 * Math.random(),
// i * i + 10);
Point p = new Point(100 * Math.random(), 100 * Math.random(),i * i + 10);
pointMap.put(new Integer(p.index), p);
pointSet1[i] = p;
}/*
问题:1.pointMap中的顺序是否和pointSet1的顺序是一样的?不一样的话怎样保证是按顺序添 加进去的,这个顺序对我的程序很重要而且要用到HashMap这种数据结构或类似的,即有键/值。有没有别的方法或数据结构可以实现呢??
2.怎样将pointMap中的所有value放到pointSet2中???
最好能帮我把代码写出来,本人初学,很多东西不懂,谢谢各位了:)
*/ }
}
2。HashMap有个values方法的,然后你循环一下添加到pointSet2中不就可以了
import java.util.*;class Point {
double x;
double y;
int index;
public Point(double x, double y, int index) {
this.x = x;
this.y = y;
this.index = index;
}
}class Test {
private static final int N = 20;
public static void main(String[] args) {
Map pointMap = new LinkedHashMap();
Point[] pointSet1 = new Point[N];
Point[] pointSet2 = new Point[N];
for (int i = 0; i < N; i++) {
// pointSet1[i] = new Point(100 * Math.random(), 100 * Math.random(),
// i * i + 10);
Point p = new Point(100 * Math.random(), 100 * Math.random(),i * i + 10);
pointMap.put(new Integer(p.index), p);
pointSet1[i] = p;
}
for(int i=0;i<pointMap.size();i++){
pointSet2[i] = (Point)pointMap.get(i*i+10);
}
System.out.println(pointMap);
//System.out.println(Arrays.toString(pointSet1));
System.out.println(Arrays.toString(pointSet2));
}
}
LinkedHashMap是jdk1.4才有的吧,能不能不用LinkedHashMap而能解决我的问题呢?
这样岂不是要我写一个LinkedHashMap来,晕死!