1

I'm working on a program that requires a lot of indices for various arrays. I thought, that one of the methods for doing so would be to have an array that holds all of the indices. For example:

int[] indices = {1, 2, 3, 4, 5};
char[] chars = {'a', 'b', 'c', 'd', 'e'};

The result being "a" would be outputted once, "b" twice, etc.

What would be the best way to go about doing this?

T145
  • 1,415
  • 1
  • 13
  • 33
  • 1
    Please explain the actual problem. Not only is this a case where something like a map will do what you described, it isn't indexing. – chrylis -cautiouslyoptimistic- Oct 03 '14 at 20:32
  • I would use Arrays only when you don't have other solutions (or when an Array is appropriate), what about a Map? – Marco Acierno Oct 03 '14 at 20:37
  • Well, the indexing is the end result, and this is just the process to get to that point. I believe I explained the scenario thoroughly; is there any thing that's abstruse? Basically it's just using the `indexes` array as a determinant for manipulating the `chars` array. – T145 Oct 03 '14 at 20:38
  • Java is an object-oriented language. Drop the C-style approach, and store an array of some CharCounter object that has both a char and int field. – Thorn G Oct 03 '14 at 20:47
  • What you are looking for is a dictionary datastructure. – anu Oct 03 '14 at 21:35

3 Answers3

1

It seems that a lot of my answers use HashMap these days. I feel like its use is underestimated, specifically because it is so versatile at handling associated data.

HashMap<Char, Integer> foo = new HashMap<Char, Integer>();
foo.add('a', 1);
foo.add('b', 2);
foo.add('c', 3);
foo.add('d', 4);
foo.add('e', 5);

for(Entry<Char, Integer> e : foo.getEntrySet()) {
    for(int i = 0; i < e.getValue(); i++) {
        System.out.print(entry.getKey());
    }
}

This, of course, assumes you don't have a preference for order. If you do, then instead you should use an ArrayList and an Object that stores a character and an Integer.

Creating multiple arrays that depend on each other is relatively unsafe, so you might as well create an Object that handles everything for you.

Compass
  • 5,867
  • 4
  • 30
  • 42
  • Do you really need *exactly* `HashMap` here? If not, please declare it as `Map`. And I think, that today it would be correct to use diamond syntax instead instead of repeating yourself with ``. – Dmitry Ginzburg Oct 03 '14 at 20:50
1

The better Data Structure for your goal is Map interface

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

Map Interface has various implementions:

  1. HashMap : The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

  2. TreeMap: The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.

  3. LinkedHashMap:This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.

visual presentation:

╔══════════════╦═════════════════════╦═══════════════════╦══════════════════════╗
║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap    ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║  no guarantee order ║ sorted according  ║                      ║
║   Order      ║ will remain constant║ to the natural    ║    insertion-order   ║
║              ║      over time      ║    ordering       ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║  Get/put     ║                     ║                   ║                      ║
║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)         ║
║ containsKey  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║   NavigableMap    ║                      ║
║  Interfaces  ║         Map         ║       Map         ║         Map          ║
║              ║                     ║    SortedMap      ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║                   ║                      ║
║     Null     ║       allowed       ║    only values    ║       allowed        ║
║ values/keys  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║              ║   Fail-fast behavior of an iterator cannot be guaranteed       ║
║   Fail-fast  ║ impossible to make any hard guarantees in the presence of      ║
║   behavior   ║           unsynchronized concurrent modification               ║
╠══════════════╬═════════════════════╦═══════════════════╦══════════════════════╣
║              ║                     ║                   ║                      ║
║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked     ║
║              ║                     ║                   ║       buckets        ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║      Is      ║                                                                ║
║ synchronized ║              implementation is not synchronized                ║
╚══════════════╩════════════════════════════════════════════════════════════════╝

Read about HashMap

Read about TreeMap

Read about LinkedHashMap

source for visual presentation

Community
  • 1
  • 1
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • Basically what I was testing the most were a bunch of for loops that would preform the logic to accomplish this. The main reason why I don't want to go w/ a map is because I don't want to say "mymap.add( ... )" over and over again, or have a for loop do it for me that uses data from the arrays I've already set up and put said data in the map. – T145 Oct 03 '14 at 22:56
  • @T145 adding info to map uses put function. is there any reason that you don't want to use map? – Kick Buttowski Oct 03 '14 at 22:59
  • Well, that's just "mymap.put( ... )"; the reasons still stand. – T145 Oct 04 '14 at 04:21
  • would you like to share your reason ? – Kick Buttowski Oct 05 '14 at 02:53
  • Yes; I feel as though it would be great to use arrays and use maybe 10 lines for the logic rather than using way more than that just to supply inputs. If there were a way to translate my arrays into a map efficiently, then that would be acceptable. – T145 Oct 05 '14 at 13:08
0

Since I believe you do want to iterate your list in order, a Map is not suitable here. The better approach is to realize that you're in an object-oriented language; create an object to model your data:

class CharCounter {
  private final char toPrint;
  private final int times;
  public CharCounter(final char toPrint, final int times) {
    this.toPrint = toPrint;
    this.times = times;
  }
}

CharCounter[] arr = new CharCounter[]{ new CharCounter('a', 1), new CharCounter('b', 2), ...};
Thorn G
  • 12,620
  • 2
  • 44
  • 56
  • Not necessarily. http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html – anu Oct 03 '14 at 21:37