views:

993

answers:

3

Hello,
I have a Map where Coords is defined as so:

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);
     }
    }

(not very good, I know, please don't tease me.) How can I now create a String where the characters are mapped from this map, for example:

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 !
                               //      !

Thanks,
Isaac Waller
(note - it's not homework)

+5  A: 
  1. Create a comparator which can sort Coords by y and then x:

    int d = c1.y - c2.y;
    if (d == 0) d = c1.x - c2.y;
    return d;
    
  2. Create a sorted map:

    TreeMap<Coords, Character> sortedMap = new TreeMap(comparator);
    sortedMap.putAll(map); // copy values from other map
    
  3. Print the values of the map in order:

    for (Character c: map.values()) System.out.print(c);
    
  4. If you need newlines:

    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);
    }
    
Aaron Digulla
This works for X, but then Y is ignored.
Isaac Waller
It's not addAll, it's putAll
Isaac Waller
putAll(): Fixed. The comparator will first sort by Y. If Y is the same for two chars, they will be sorted by X. So I'm not sure what you mean by "This works for X".
Aaron Digulla
There are no newline characters printed. This is fairly good though so I'll accept it.
Isaac Waller
In this case, keep the current Y value in a local variable and use the Entity interface of the map. When the Y value changes, print a newline.
Aaron Digulla
A: 

I suggest you add a toString method to Coord or use the Point class.

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();

If you want to layout the characters you could use multi dimensional array.

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));
Peter Lawrey
A: 

this helped me with getting the idea of coords storing. even it's not good, i say thank you<3

Murka