Java array with alphanumeric indices

Asked

Viewed 73 times

-4

Merry Christmas to all!

How do I, in java, that array?

{
   "Aluno" => "fulano",
   "Idade" => 33
}

I thought about Arraylist, but it didn’t work out

I thought about List, also did not work

Think about String[] , same thing

They don’t seem to accept indexes.

  • 4

    Use Map: https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html

  • 2

    Or create a class with the attributes you want.

1 answer

2


In your case the ideal would be an object that concentrates these attributes and a list of this object. I created a use case that might resemble your need, a Student class, a Class Class with Student Add Method:

Java student.

public class Aluno {

    private String nome;
    private int idade;
    private String matricula;


    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public String getMatricula() {
        return matricula;
    }

    public void setMatricula(String matricula) {
        this.matricula = matricula;
    }
}

Java class.

import java.util.ArrayList;
import java.util.List;

public class Turma {

    private String codigo;
    private List<Aluno> alunos;


    public String getCodigo() {
        return codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public List<Aluno> getAlunos() {
        return alunos;
    }

    public void setAlunos(List<Aluno> alunos) {
        this.alunos = alunos;
    }

    public void addAluno(Aluno aluno){
        if(this.alunos == null){
            this.alunos = new ArrayList<Aluno>();
            this.alunos.add(aluno);
        }else{
            this.alunos.add(aluno);
        }
    }
}
  • Thank you! It will be a solution! An object does it! I’m very used to PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.