-3

I need something that in PHP would look (2D array):

Array
(
[0] => Array
    (
        [name] => foo
        [desc] => some foo
    )

[1] => Array
    (
        [name] => bar
        [desc] => some bar
    )

)

All the java examples say that I should create "Integer [][] data;" or "String [][] data;" but here I have Int (index) and String... how to mix it? How to populate it ...datas[i]["name"] = "aa" ?? How to read it in another Loop like:

for(int i=start;i<start;i++)
{
   value = data[i]["name"]...???
}
Alex Burton
  • 49
  • 1
  • 8

1 Answers1

0

As Pshemo say, java use only int as index for array.

You have plenty of solutions to achieve your objective. I will just present tree of them, both use an object container. Java is object programming, use them.

// Class declaration
public class SimpleContainer {

    private final String name;
    private final String description;

    public SimpleContainer(final String name, final String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }}

1, Use an array of object (not recommended):

 SimpleContainer[] simpleContainers = new SimpleContainer[3];
 simpleContainers[0] = new SimpleContainer("name 1", "description 1");
 simpleContainers[1] = new SimpleContainer("name 2", "description 2");
 simpleContainers[2] = new SimpleContainer("name 3", "description 3");

 for (int i = 0; i < simpleContainers.length; i++) {
        System.out.println(String.format("I am [%s] and my description is [%s]",
         simpleContainers[i].getName(),
         simpleContainers[i].getDescription()));
}

  1. Use a list instead of your array

In Java a rule of thumb is to use array only for primitive type (like int, bytes, ...). And use list for others types. For more details, read:

  1. When to use a List over an Array in Java?
  2. more

Some simple example of list usage (same object) :

List<SimpleContainer> myList = new ArrayList<SimpleContainer>();
myList.add(new SimpleContainer("name 1", "description 1"));
myList.add(new SimpleContainer("name 2", "description 2"));
myList.add(new SimpleContainer("name 3", "description 3"));

// Use iterator (support remove object for most list implementations).
        Iterator<SimpleContainer> it = myList.iterator();

while(it.hasNext()) {
     SimpleContainer simpleContainer = it.next();
     System.out.println(String.format("I am [%s] and my description is [%s]",
     simpleContainer.getName(),
     simpleContainer.getDescription()));
}

// Or simple loop.
for (SimpleContainer simpleContainer : myList) {
     System.out.println(String.format("I am [%s] and my description is [%s]",
     simpleContainer.getName(),
     simpleContainer.getDescription()));
}

Understand the collections in Java is very important, just check a tutorial like : Simple tutorial about collections


  1. Use a hashmap who represent an association between two objects. Hashmap is the preferred solution if the main action you want is to find any association.

     HashMap<String, String> myMap = new HashMap<>();
     myMap.put("name 1", "description 1");
     myMap.put("name 2", "description 2");
     myMap.put("name 3", "description 3");
    
     String description = myMap.get("name 1");
    
     Iterator<Map.Entry<String, String>> it =    myMap.entrySet().iterator();
    
      while (it.hasNext()) {
    
         Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
     }
    

  1. Maybe you want to use a double index with int and string, in this case you can use one example of this page : Double key indexing

  1. Finally you can use predicate (java 8 or guava librarie). There is an example of usage of guava predicate.

    public void ExamplePredicate() {
    List<SimpleContainer> myList = new ArrayList<SimpleContainer>();
    myList.add(new SimpleContainer("name 1", "description 1"));
    myList.add(new SimpleContainer("name 2", "description 2"));
    myList.add(new SimpleContainer("name 3", "description 3"));
    
    // Get one index :
    System.out.println(myList.get(1).getDescription());
    
    // Try to find an entry with name.
    Optional<SimpleContainer> optContainer = Iterables.tryFind(myList, new NameContainerPredicate("name 1"));
    if (optContainer.isPresent()) {
        System.out.println(optContainer.get().getDescription());
    }
    
    // Try to find an entry with name between two index.
    Optional<SimpleContainer> optContainer2 = Iterables.tryFind(myList.subList(1, 2), new NameContainerPredicate("name 1"));
    if (optContainer2.isPresent()) {
        System.out.println(optContainer2.get().getDescription());
    } else {
        System.out.println("No entry found");
    }
    
    // Get all entry with given name.
    List<SimpleContainer> containersList = Lists.newArrayList(Iterables.filter(myList.subList(1, 2), new NameContainerPredicate("name 1")));
    for (SimpleContainer simpleContainer : containersList) {
        System.out.println(String.format("Name [%s]  description [%s]", simpleContainer.getName(), simpleContainer.getDescription()));
    }
    }
    
    private static class NameContainerPredicate implements Predicate<SimpleContainer> {
    
    private final String name;
    
    public NameContainerPredicate(final String name) {
        this.name = name;
    }
    
    @Override
    public boolean apply(@Nullable final SimpleContainer input) {
        return input != null && equal(input.getName(), name);
    }
    }
    
Community
  • 1
  • 1
Manticore
  • 441
  • 5
  • 24
  • Or just use a hashmap, since it represents an "associative array" which is what PHP uses. – Bauss May 18 '15 at 23:22
  • Thanks guys. If I read well your 1-2 solutions Manticore offer simple List nothing more. I need 2D array. HashMap is interesting but I cannot find example how to get concrete index from it; what I'm doing in PHP with array[index][key]. For instance I want third index from Hashmap.... – Alex Burton May 19 '15 at 08:35
  • Have you an example of usage, because I think you want an array but you don't need one. – Manticore May 19 '15 at 10:45