2

In PHP I can make:

$array = array();

for($i = 0; $i < 10; $i++){
   $array[$i]['title'] = "title" . $i;
   $array[$i]['text'] = "text" . $i;
}

How can i make it in Java? Why I can't use text in index arrays? Maybe i must use Object, but how?

Next problem - in Java i must declare array with numbers of elements, but sometimes I get a list that does not know how much has elements and on listing i use instruction "IF" also to skip some of the elements.

4
  • 1
    Welcome to Stack Overflow, please take the Tour. Please read How do I ask a good question?. Commented Aug 21, 2014 at 20:40
  • 1
    Java best practice would be to use a proper class for this rather than an untyped array or Map. Commented Aug 21, 2014 at 20:40
  • 1
    Please take a bit of time to go through a Java book for beginners, or follow Oracle tutorials at docs.oracle.com/javase/tutorial , with particular attention to docs.oracle.com/javase/tutorial/java/index.html Commented Aug 21, 2014 at 20:51
  • +1 to Louis Wasserman. Java is an type-safe, OO language. Assuming that you want to store multiple messages, each having a title and a text, you should create a Message class, with two attributes title and text, and use a List<Message>. Commented Aug 21, 2014 at 20:54

3 Answers 3

4

You can make a List<Map<String, String>>:

List<Map<String, String>> listOfMap = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    Map<String, String> map = new HashMap<>();
    map.put("title", "title" + i);
    listOfMap.add(map);
}

Still, instead using a Map you may create a proper class that holds these attributes:

public class Entity {
    private String title;
    private String text;
    //getters and setters...
}

List<Entity> entityList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    Entity entity = new Entity();
    entity.setTitle("title" + i);
    entityList.add(entity);
}

More info:

Since you're working with Java 6, use the complete assignment:

List<Map<String, String>> listOfMap = new ArrayList<Map<String, String>>();
//...
Map<String, String> map = new HashMap<String, String>();
//...
List<Entity> entityList = new ArrayList<Entity>();
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but for your first example i have error: "'<>' operator is not allowed for source level below 1.7". I have Android project.
@peksak: if your question is about android, add the android tag to your question.
1

The Java array is designed to be a numerical-index contiguous fixed-width collection with order that allows duplicated.

For fields such as title or text you may consider making a class that defines those fields. If the set of fields names may differ between objects, a HashMap<String, String> would do for string keys and string values.

To make an array whose length may change, use an ArrayList<Foo> where Foo is the class of objects you want the list to contain.

1 Comment

Thank you, but could you give an example ready? I am new to Java.
1

An important note about PHP is that almost everything is treated as a hashmap. That means an 'array' is really a map from some key to a value: that key can be anything because PHP is weakly typed.

Java is a "strictly typed language", meaning it's concept of an array is simply an indexed sequence of elements:

String arr[] = new String[3];//This array will be numerically indexed by integers and only integers.
//Note, too, that it will be length three, and never any other length.

Note that the above uses an 'array primitive', where the array does not derive from Java's Object. You can use a full class by using a List class-based object.

If you want to get the same functionality as in PHP you have to use a map of some sort. For instance:

Map<String, Object> arr = new HashMap<String, Object>();
for (int x = 0; x < 10; x++) {
  arr.put(Integer.toString(x), "title" + x);
}

Note that Maps in Java are not 'ordered'. Note that we are also cheating here by casting x to a string so that the Map will accept it as a key: because of strict typing the above declaration will only take String objects as a key. You could change the definition to take any Object, but then it will be even more difficult to reason about what that array is.

Because your example is a multi-dimensional array, you will have to decide in Java what represents each of those dimensions. Some possibilities:

List<Integer, Map<String, Object>> useLists;
Map<String, Object> usePrimitiveArrays[];

6 Comments

thanks, but i have error in line with: arr.put((String)x, "title" + x); - "Cannot cast from int to String"
I downvoted you for the cast from a primitive to String -- you need to use Integer.toString(int).
Yes, I always forget that syntax violations are worth downvotes.
I'm not sure if that's sarcasm, but in this case, with a user clearly unfamiliar with the syntax, the details are important. However SO won't let me retract the downvote after you've fixed it for some reason. :(
You are, of course, welcome to vote however you want. However, overall I think it is more useful to the community if you engage the 'edit' option and fix the problem, especially when it is orthogonal to the main thrust of the post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.