objects with key: value in Java

Viewed 57

I have just started to learn Java. Read a small book but I didnt catch information about key: value objects.

for example in javascript:

let car = {
           type:"Fiat", 
           model:"500", 
           color:"white"
           };

but in java there is only classes, which create an object:

public class CarObject {
    public static void main(String[] args) {
    Car car = new Car("Fiat", "500", "White");
    }
}
class Car{
    String type;
    String model;
    String color;
    public Car(String type, String model, String color){
        this.color = color;
        this.model = model;
        this.type = type;
    }
}

So, my question is if in Java language there is no such thing like key: value. Or there is no sense to use it, because of used classes?

3 Answers

Key:Value pairs concept exists in java and for that you can always utilize Map Interfaces. The Map interface in Java is part of the Collections framework and provides the functionality of map data structure; which means mapping a key to a value.

However, a class is a blueprint for creating new objects/entities; such entity or object when created has its own state and behavior.

Map data structure and Class/Object have no contradiction. A Map could be used to define an objects state or be produced as the result of an objects behavior.

What you want is the Map interface and its implementations.

The most used one is HashMap. Which you declare like:

Map<typeOfKey,typeOfValue> aMap = new HashMap<typeOfKey,typeOfValue>()

So, my question is if in Java language there is no such thing like key: value.[1] Or there is no sense to use it, because of used classes? [2]

[1] There is what ever wanted to be in each programming language. Maybe, some programming languages have specific features (eg: OOP, functional Interface, various data types). Do your own if what is provided is not enough.

[2] Key-Values reflect better a paradigm of programing, saying other a way of convenient storage which latter will ease the programming work.

One of java features is Map- type a List of elements stored as <key,value>, but this is not necessary the only way (better an alternative).

With a small example, Cat(identifier, name) and if wanted to store use a List of type Cat List<Cat>. Name is not required to be a property (cat name), can be what ever you wanted (an instance). Cat(id, (name, hair color, tail length)) -> instance of dog friend.

Related