1

Coords が次のように定義されている Map があります。

class Coords {
        int x;
        int y;
        public boolean equals(Object o) {
            Coords c = (Coords)o;
            return c.x==x && c.y==y;
        }
        public Coords(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }
        public int hashCode() {
            return new Integer(x+"0"+y);
        }
    }

(あまり良くありません。私をからかわないでください。) このマップから文字がマップされた文字列を作成するにはどうすればよいですか。たとえば、次のようになります。

Map<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new Coords(0,0),'H');
map.put(new Coords(1,0),'e');
map.put(new Coords(2,0),'l');
map.put(new Coords(3,0),'l');
map.put(new Coords(4,0),'o');
map.put(new Coords(6,0),'!');
map put(new Coords(6,1),'!');
somehowTransformToString(map); //Hello !
                               //      !

ありがとう、
Isaac Waller
(注 - 宿題ではありません)

4

2 に答える 2

6
  1. Coords を y、次に x でソートできるコンパレータを作成します。

    int d = c1.y - c2.y;
    if (d == 0) d = c1.x - c2.y;
    return d;
    
  2. ソートされたマップを作成します。

    TreeMap<Coords, Character> sortedMap = new TreeMap(comparator);
    sortedMap.putAll(map); // copy values from other map
    
  3. マップの値を順番に出力します。

    for (Character c: map.values()) System.out.print(c);
    
  4. 改行が必要な場合:

    int y = -1;
    for (Map.Entry<Coords, Character> e: map.entrySet()) {
        if (e.y != y) {
            if (y != -1) System.out.println();
            y = e.y;
        }
        System.out.print(c);
    }
    
于 2009-05-25T16:24:39.893 に答える
1

toString メソッドを Coord に追加するか、Point クラスを使用することをお勧めします。

Map<Point, Character> map = new HashMap<Point , Character>();
map.put(new Point(0,0),'H');
map.put(new Point(1,0),'e');
map.put(new Point(2,0),'l');
map.put(new Point(3,0),'l');
map.put(new Point(4,0),'o');
map.put(new Point(6,0),'!');
map put(new Point(6,1),'!');
String text = map.toString();

文字をレイアウトしたい場合は、多次元配列を使用できます。

char[][] grid = new char[7][2];
grid[0][0] ='H';
grid[0][1] ='e';
grid[0][2] ='l';
grid[0][3] ='l';
grid[0][4] ='o';
grid[0][6] ='!';
grid[1][6] ='!';
for(char[] line: grid) System.out.println(new String(line));
于 2009-05-25T16:42:39.397 に答える