来自XY坐标的Java字符串

Isa*_*ler 1 java string map coordinates coordinate-systems

我有一个地图,Coords定义如下:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

(不是很好,我知道,请不要取笑我.)我现在如何创建一个字符串,从这个地图映射字符,例如:

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 !
                               //      !
Run Code Online (Sandbox Code Playgroud)

谢谢,
Isaac Waller
(注意 - 这不是作业)

Aar*_*lla 6

  1. 创建一个比较器,可以用y和x对Coords进行排序:

    int d = c1.y - c2.y;
    if (d == 0) d = c1.x - c2.y;
    return d;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建有序地图:

    TreeMap<Coords, Character> sortedMap = new TreeMap(comparator);
    sortedMap.putAll(map); // copy values from other map
    
    Run Code Online (Sandbox Code Playgroud)
  3. 按顺序打印地图的值:

    for (Character c: map.values()) System.out.print(c);
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    }
    
    Run Code Online (Sandbox Code Playgroud)