Associative arrays in Java - java

I'm from a PHP background, and I'm trying to create a multidimentional array with a difficulty in understanding the Java way of doing things. I thought this could be achieved using JSON and the GSON library, but I'm failing to understand how this is done having followed several tutorials online.
Here is what I'm after in PHP, how can I achieve the same thing in Java?
function creatCars($id) {
$aCars = array(
0 => array(
'name' => 'vauxhall',
'doors' => 5,
'color' => 'black',
),
1 => array(
'name' => 'peogeot',
'doors' => 3,
'color' => 'red',
),
);
return $aCars[$id];
}
function printFirstCarName($sName) {
$aCar = createCars(0);
echo $aCars['name'];
}
//prints "vauxhall"
printFirstCarName();

Arrays in PHP are not the same as arrays in Java. Here are the differences:
PHP:
PHP arrays are actually dictionaries. They store a value for each key, where a key can be an integer or a string. If you try to use something else as a key, it will be converted to either an integer or a string.
Java:
Arrays in Java
Java arrays are not associative in the same way as they are in PHP. Let's start with one-dimensional arrays in Java:
A one-dimensional array in Java has a fixed length (that cannot be changed) and each key is an integer in the range of 0 to array.length - 1. So keys, actually called indexes, are always integers. Also, in Java, if you have an array with the keys 2 and 4, you also have (at least) the keys 0, 1 and 3, because the length has to be at least 5 then.
Arrays in Java also have exactly one type and each values in the array can only be of the specified type. Neither size nor type of an array can be changed.
When you create an array in Java, you have two possibilities:
explicitly specify the length when creating the array
String[] words = new String[4];
The variable words now holds an array of type String with the length a length of 4. The values of all indexes (0 to 3) are initially set to null.
specify elements when creating the array
String[] words = new String[] {"apple", "banana", "cranberry"};
The variable words now holds an array of type String with a length of 3. The elements contained are as specified with the first element bound to index 0, the second element bound to index 1, and so on.
You can think of multi-dimensional arrays as of an array which holds arrays. A 2-dimensional array could look like this:
String[][] twoD = new String[][] {
{"apple", "banana", "cranberry"},
{"car", "ship", "bicycle"}
}
For this twoD[0][2] would be "cranberry" and twoD[1][1] would be "ship". But the number of dimensions of an array does not influence the fact that the keys are integers.
Maps in Java:
Even though Java has no built-in language construct for associative arrays, it offers the interface Map with various implementations, e.g. HashMap. A Map has a type of which the keys are, and a type of which the values are. You can use maps like this:
HashMap<String, String> map = new HashMap<String, String>();
map.put("car", "drive");
map.put("boat", "swim");
System.out.println("You can " + map.get("car") + " a car.");
System.out.println("And a boat can " + map.get("boat") + ".");
This will output:
You can drive a car.
And a boat can swim.
The answer:
The one-to-one way in Java
The answer to your question is that it is not really possible in a reasonable way becasue some of your values are strings, and some are integers. But this would be the most similar code to your PHP array:
//array of HashMaps which have Strings as key and value types
HashMap<String, String>[] cars = new HashMap<String, String>[2];
HashMap<String, String> first = new HashMap<String, String>();
first.put("name", "vauxhall");
first.put("doors", "5");
first.put("color", "black");
HashMap<String, String> second = new HashMap<String, String>();
second.put("name", "peogeot");
second.put("doors", "3");
second.put("color", "red");
//put those two maps into the array of maps
cars[0] = first;
cars[1] = second;
This solution is not very handy, but it is the way that comes closest to your given datastructure.
The cuter way in Java
It seems however, that each of the entries in your PHP array has exactly three properties: name, doors and color. In this case, you may want to create a class Car with these member variables, and store them in an array. This would look like this:
public class Car {
//member variables
public String name;
public int doors;
public String color;
//constructor
public Car(String name, int doors, String color) {
this.name = name;
this.doors = doors;
this.color = color;
}
}
Now, when you have the class Car, you can create an array of all your cars like this:
Car[] cars = new Car[2];
cars[0] = new Car("vauxhall", 5, "black");
cars[1] = new Car("peogeot", 3, "red");
This is the nicer way to do this in Java.

Instead of creating 2D Array you can create 1 class Car
public class Car{
private String carName;
private String color;
private int noOfDoors;
public car(String carName,int door,String color){
this.carName=carName;
this.door=door;
this.color=color;
}
public String getCarName(){
return getCarName;
}
public void setCarName(String carName){
this.carName=carName;
}
// Same getters(getXXX) and setters(setXXX) for other Variables
}
Now create Objects of above class
Car audi=new Car("audi",2,"Black");
Car bmw=new Car("bmw",4,"White");
Now add these to the List<Cars>
List<Car> listOfCars=new ArrayList<Car>();
listOfCars.add(audi);
listOfCars.add(bmw);
Now to Print First Car Name
Car firstCar=listOfCars.get(0);
System.out.println(firstCar.getCarName()); //here getter Method Helped you

I would suggest to get familiar with HashMaps, Maps and ArrayLists. In Java and many other languages is something analogous to a video game cheat.
private static Map<Integer, HashMap<String, String> > carMap = new HashMap<Integer, HashMap<String, String> >();
But in this case you have to understand how would OO principles help you. You can create a class with Car objects and populate a HashMap etc.
class Car {
private String name, colour;....
public Car(){....}
public void setValues(...){....}
}
To achieve better what you want to I would suggest reading this and getting familiar with some design patterns. It's a bit further down the road, but do it for the lulz and seeing what it's out there. Example : http://howtodoinjava.com/2012/10/23/implementing-factory-design-pattern-in-java/
When moving from scripting to strongly typed languages sometimes you have to change your way of thinking too.

Firstly you should create class Car i.e:
public class Car {
enum ColorType {
BLACK, RED;
}
private String name;
private int doors;
private ColorType color;
Car(String name, int doors, ColorType color) {
this.name = name;
this.doors = doors;
this.color = color;
}
public String getName() {
return name;
}
public int getDoors() {
return doors;
}
public ColorType getColor() {
return color;
}
}
And now you can use arrays but better for you will be use ArrayList:
List<Car> cars = new ArrayList<Car>();
cars.add(new Car("vauxhall", 5, BLACK));
cars.add(new Car("peogeot", 3, RED));
for (Car car : cars ) {
System.out.println("Car name is: " + car.getName());
}

It seems what you are trying to achive is an 'array of cars'. So instead of creating an array of arrays, I recommend to literally implement an 'array of cars'.
To do this, I would define the car first, possibly in a different file:
class Car {
//you can make these private and use 'get' and 'set' methods instead
public String name;
public String color;
public int doors;
public Car() {
name = "";
color = "";
doors = 0;
}
public Car(String name, String color, int doors) {
this.name = name;
this.color = color;
this.doors = doors;
}
}
You can use the car structure in an another module like this:
Car[] cars = new Car[100]; //create one hundred cars
cars[11].doors = 4; //make the 12th car's number of doors to 4
You can use more flexible data structures, like Vectors, List, Maps, etc... Search for Java collections, you will find tones of info.

Java is not a loosely typed language, you have to tell the compiler what each variable is going to be. And to store this kind of structured data in Java, you should first declare a class and instantiate objects of that class. Following is how you would achieve the same thing as your PHP code:
class Car {
private String name, color;
private int doors;
Car(String name, int doors, String color) {
this.name = name;
this.doors = doors;
this.color = color;
}
public String getName() {
return this.name;
}
}
public class CarMainClass {
public static void main(String[] args) {
Car[] aCars = new Car[2];
aCars[0] = new Car("vauxhall", 5, "black");
aCars[1] = new Car("peogeot", 3, "red");
System.out.println("First car name is: " + aCars[0].getName());
}
}
Compile using:
javac CarMainClass.java
Then run:
java CarMainClass
You will have to learn the basics of Java first to understand the above code.

Related

How to fill arrays with object parameter based of a value?

If I have a certain number of objects which each take multiple parameters, how can I fill an array with one particular parameter for all objects, but have the order of the elements in the array based off another parameter. For example, I have this code:
public CollegeList(double gpa, int act, int sat, String name, String location){
this.gpa = gpa;
this.act = act;
this.sat = sat;
this.name = name;
this.location = location;
if(act/36.0>sat/2400.0){
this.score = 0.6*gpa*25.0+0.4*(act/36.0)*100.0;
}else{
this.score = 0.6*gpa*25.0+0.4*(sat/2400.0)*100.0;
}
this.scoreDistance = Math.abs(this.score-MainActivity.scoreDouble)/MainActivity.scoreDouble;
}
public double getGpa(){
return this.gpa;
}
public int getAct(){
return this.act;
}
public int getSat(){
return this.sat;
}
public String getName(){
return this.name;
}
public String getLocation(){
return this.location;
}
public double getScore(){
return this.score;
}
public double getScoreDistance(){
return this.scoreDistance;
}
Here, I would like the name parameter for all objects that I may create to populate a String array, but have those names go in ascending order by the double scoreDistance in the array. I'm sorry if the wording of this question is bad, but I hope it makes sense.
1) Create a CollegeList[] or ArrayList<CollegeList> containing the objects you want to sort.
2) Create a Comparator<CollegeList> that compares two CollegeList objects by comparing the scoreDistance. In Java 8 (yes, I know this isn't available for Android, but other readers may find this useful):
Comparator<CollegeList> compareByScoreDistance = (CollegeList a, CollegeList b) -> Double.compare(a.getScoreDistance(), b.getScoreDistance());
In Java 7:
Comparator<CollegeList> compareByScoreDistance = new Comparator<CollegeList>() {
#Override
public int compare(CollegeList a, CollegeList b) {
return Double.compare(a.getScoreDistance(), b.getScoreDistance());
}
};
3) Sort the array or ArrayList using the comparator. If it's an array:
Arrays.sort(theArray, compareByScoreDistance);
If it's an ArrayList, use Collections.sort instead of Arrays.sort.
4) Now you can create the string array by going through the CollegeList[] or ArrayList<CollegeList> and creating an array or ArrayList using getName(). For example, if your list is an ArrayList, then you can use this from #user3717646's answer:
for (CollegeList collegeList : theList) {
nameList.add(collegeList.getName());
}
Or using Java 8:
String[] names = theList.stream().map(CollegeList::getName).toArray(String[]::new);
or
ArrayList<String> names = new ArrayList<>(theList.stream().map(CollegeList::getName).collect(Collectors.toList()));
EDIT: Code has now been tested, and several mistakes fixed.
Try Using ArrayLists. Following sample code is given for two CollegeList objects.
ArrayList<CollegeList> collegeLists=new ArrayList<>(); // To store all CollegeList Objects
ArrayList<String> nameList=new ArrayList<>(); // To store Names
CollegeList cl1=new CollegeList(12, 45, 5, "Name1", "Location1");
CollegeList cl2=new CollegeList(12, 45, 5, "Name2", "Location2");
collegeLists.add(cl1);
collegeLists.add(cl2);
for (CollegeList collegeList : collegeLists) {
nameList.add(collegeList.getName());
}
collegeLists stores all CollegeList objects.
then you can get each and every parameter using get methods and put the in to seperate aarraylists.
If you want to sort the arraylist, You can uose Collections.sort(nameList); to do it.

How to get value from TreeMap in Java?

My problem is can't get an object "Item" (value) from my Treemap. I need send that info to my GUI class and display it in JList to get a select list, so can easily select and add songs to playlist, but only what I get as an output is "01, 02, 03, 04, 05" (key). Please help, because I'm beginner and have no idea what to do.
public class LibraryData {
private static class Item {
Item(String n, String a, int r) {
name = n;
artist = a;
rating = r;
}
// instance variables
private String name;
private String artist;
private int rating;
private int playCount;
public String toString() {
return name + " - " + artist;
}
}
private static Map<String, Item> library = new TreeMap<String, Item>();
static {
library.put("01", new Item("How much is that doggy in the window", "Zee-J", 3));
library.put("02", new Item("Exotic", "Maradonna", 5));
library.put("03", new Item("I'm dreaming of a white Christmas", "Ludwig van Beethoven", 2));
library.put("04", new Item("Pastoral Symphony", "Cayley Minnow", 1));
library.put("05", new Item("Anarchy in the UK", "The Kings Singers", 0));
}
public static String[] getLibrary() {
String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);
return tempa;
}
SOLUTION:
Because I've to pass the values to another class:
JList tracks = new JList(LibraryData.getLibrary());
I made something like that and it's works
public static Object[] getLibrary() {
Collection c = library.values();
return c.toArray(new Item[0]);
Thank You guys, after 10 hours I finally done it!
}
With this code that you have:
String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);
You are getting all keys from the map. If you want all values, then use:
library.values();
Finally, if you need to get a value by key use V get(Object key):
library.get("01");
Which will return you the first Item from the map.
It's not very clear which one of these you want, but basically these are the options.
** EDIT **
Since you want all values you can do this:
library.values().toArray()
JList expects an array or vector of Object so this should work.
If you want to get value and key by position, you can use:
key: library.keySet().toArray()[0]
value: library.get(key);
OR (if you just want value)
library.values().toArray()[0];
You can use the ArrayList:
1 - The best for flexible-array managing in Java is using ArrayLists
2 - ArrayLists are easy to add, get, remove and more from and to.
3 - Treemaps are a little... arbitrary. What I say is that if you use the get(Object o) method from a Treemap, the Object o must be a key, which is something not very flexible.
If you want them, use this code:
import java.util.ArrayList;
import com.example.Something; // It can be ANYTHING
//...
ArrayList<Something> somethingList = new ArrayList<Something>();
//...
somethingList.add(new Something("string", 1, 2.5, true));
//...
boolean isSomething = somethingList.get(somethingList.size() - 1); // Gets last item added
//...
int listSize = somethingList.size();
//...
somethingList.remove(somethingList.size() - 1); // Removes last item and decrements size
//...
Something[] nativeArray = somethingList.toArray(new Something[somethingList.size()]); // The parameter is needed or everthing will point to null
// Other things...
Or the classic Treemap:
Object keyAtIndex0 = library.keySet.toArray(new Object[library.size()])[0];
Object value = library.get(keyAtIndex0);
Good Luck!
I was returning a list of string values as treemap value. The used approach is
private Map<String, TreeSet<String>> result;
TreeSet<String> names= result.get(key);
for(String contactName: names){
print contactName;
}

Java - clone class based on array

I have a class called NewClass, and inside this class I have another class called people. I want to make clones of the people class, and have them with different values and names; however, I want these classes named based on a String array.
Lets say I have a String array with 5 words:
String[] array = new String[] { "first", "second", "third", "fourth", "fifth" };
And I have a class with a few variables like:
class people
{
String name;
int id;
}
Is it possible to clone or create a new class, using "people" as the model with the Strings from array? I've tried this so far and it doesn't work:
for (int i = 0; i < array.length; i++)
{
people array[i] = new people();
}
Also, how would these classes be accessed from outside the "NewClass"; would it be possible to access like this:
class OtherClass
{
NewClass myclass = new NewClass();
System.out.println(myclass.first.name);
}
You really should read a Java tutorial.
Your code is wrong at so many levels (starting with not following Java naming conventions, and improperly using the technical term clone for transforming an array of strings into an array of other objects), its hard to give you a concise answer.
Really, read a Java tutorial. They'll tell you how to make an People[] array. Or even better: an ArrayList<People>.
From reading a well-written tutorial or book you will learn much more than from the short answers you can expect to get here. See: the tutorials and books are often written by people who teach professionally...
You cannot dynamically set variable names based on Strings. You've already shown us a better example- creating an array of 'people' class and filling it with 'people' objects (Java best practices suggests using a capital at the start of class names though). You can easily set the 'name' field of the 'people' class in the same loop you used to instantiate all the 'people' objects by iterating through the String array. Then it is as simple as knowing the index of the 'people' object you want to retrieve.
peopleArray = new people[array.length];
for (int i = 0; i < array.length; i++)
{
peopleArray[i] = new people();
peopleArray[i].name = array[i];
}
Then just:
System.out.println(peopleArray[index].name);
You can simplify it by writing a constructor for the 'people' class
I'm not sure what exactly you are trying to do. But if you really want to dynamically set variable names based on Strings you need a HashMap.
Here is an example.
import java.util.HashMap;
class Person {
private String name;
private int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public String toString() {
return "Person - name = " + name + ", id = " + id;
}
}
public class MyClass {
private static HashMap<String, Person> people = new HashMap<>();
public static void main(String[] args) {
String[] keys = { "first", "second", "third", "fourth", "fifth"};
String[] names = { "Emily", "Bob", "Susan", "Bill", "Alice"};
int[] ids = {1, 2, 3, 4,5};
for(int i = 0; i < keys.length; i++) {
Person p = new Person(names[i], ids[i]);
people.put(keys[i], p);
}
System.out.println(people.get("first"));
System.out.println(people.get("second"));
}
}
But I doubt that you actually need to do this. Maybe all you want to do is set the name of the person to a string from the array. In which case you don't need the HashMap.

Is there a way to give names to row and column of a 2D array in Java?

I google it before, the answer was no but I wonder if there is any possible way.
Is there a way to give names to row and column of a 2D array in Java?
No you can't. 2D array is just array of arrays. You'll need to have 2 other arrays with names for columns and rows
Probably you can use something different (another data structure like Map) if you need to.
More dimensional arrays are normally the approach to avoid classes. For example:
String[][] persons;
persons[0][1];
If you are confronted with such a code you should first make it more readable.
public static final int FIRSTNAME = 0;
public static final int LASTNAME = 1;
persons[0][FIRSTNAME];
persons[0][LASTNAME];
A better way to encapsulate the data structure is a class:
public class Person {
private String firstname;
private String lastname;
public String getFirstname(){
return firstname;
}
public String getLastname(){
return lastname;
}
}
Person[] persons;
person[0].getFirstname();
Or if you want the change to be as minimal as necesarry:
public class Person {
public static final int FIRSTNAME = 0;
public static final int LASTNAME = 1;
private String[] personData;
public String getFirstname(){
return personData[FIRSTNAME];
}
public String getLastname(){
return personData[LASTNAME];
}
}
Make your choice
It seems that your requirement is to identify the rows. For that instead of using arrays you can use Map which are formed by unique keys.
You can define like
Map<String,ArrayList<SomeObject>> map = new HashMap<String,ArrayList<SomeObject>>();
By this way, you can put a key which can work as a row identifier as it is unique and add an entire arrayList as its value
Forget about associative arrays.You are in Java now and go for advanced way :)For this Java provides maps.You need to use the maps.
Here is a example
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map<String ,Integer> m1 = new HashMap<String ,Integer>();
m1.put("name1", 8);
m1.put("name2", 31);
m1.put("name3", 12);
m1.put("name4", 14);
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
If you need more deeply,As you are saying
is there a way to give names to row and column of a 2D array in Java?
then need to store a datastructure against a key then it is possible.You may store a Map against a key and then you will call it a multimap which will look like this
Map<X, Map<Y,Z>> map1;

creating names for linked lists while looping (Java)

I have implemented a simple linked list class and I would now like to use it in a loop. I am wondering how to best assign names to the list in each iteration of the loop.
Essentially I am looping over some integers, and I would like to just give each list the name of that integer, but I cannot say
List i = new List();
right ?
There probably is an easy way to do this, but I m not sure how, and would be grateful for
I think you're confusing the role of variables with the role of collections. From your question I gather that you want to create a list for each index in your loop, and you would like to later be able to access that list by its index:
ArrayList<LinkedList<String>> listOfLists = new ArrayList<LinkedList<String>>();
for(int i = 0; i < 10; i++)
{
LinkedList<String> list = new LinkedList();
listOfLists.add(list);
// do stuff to the list...
}
// access
LinkedList<String> thirdList = listOfLists.get(2); // index 2 = third entry
So you see, the LinkedLists are not named according to the value of i, but you can still access them by a given value of i.
First of all, if if not for learning purposes, it is highly recommended not to implement your own classes for stuff that is already implemented in libraries.
For Lists, you should check out the collection framework: http://docs.oracle.com/javase/tutorial/collections/
I am not sure what you mean by "the name of that integer".
I assume you want to create a List of elements that contain both an integer, and a String representing the name of the value that is hold in the integer.
If it is the case, the best way to do this probably is to create your own Object:
class NamedInteger {
private int value;
private String name;
public NamedInteger(int value, String name) {
this.value = value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
public void setValue(int value) {
this.value = value;
}
public void setName(String name) {
this.name = name;
}
}
The advantage of this method, is that later, if you want to add other information to your object, it is very easy to do so.
And then, just have a List of those objects....
public static void main(String[] args) {
List<NamedInteger> list = new LinkedList<NamedInteger>();
list.add(new NamedInteger(1, "Hello");
...
}

Categories