Joseph
Joseph

Reputation: 85

I want to get individual element of an arrayList in Java

I am newbie in java and I have a method that accepts 3 parameters, query the db and returns result in an arraylist form (like this [1, Java, 3, Bangalore, 10] ). How can i extract individual element so that I can assign each to a var like int id=1;String name=Java.

Below is the method that

ArrayList searchResult =jSearch.doJobSearch(techName, exp, city);
        Iterator  searchResultIterator = searchResult.iterator();
        PrintWriter out = response.getWriter();         
        String arrayList[] = new String[searchResult.size()];
        if(searchResultIterator.hasNext()){                         
            for(int i =0; i<searchResult.size(); i++){
                //searchResult.get(i)
                out.println(searchResult.get(i));
            }
        }else{
            out.println("No Job found in selected city");
        }

Upvotes: 0

Views: 1984

Answers (2)

Arun Kumar
Arun Kumar

Reputation: 2934

Create POJO (Plain Old Java Object). I am providing example how to array list is used when store Real time Object.

package com.appkart.examples;

public class Employee {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And Add Employee into Array list and get values

package com.appkart.examples;

import java.util.ArrayList;

public class Program {

    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<Employee>();

        Employee arun = new Employee(10, "Arun");
        Employee ankit = new Employee(20, "Ankit");
        Employee jon = new Employee(30, "Jon");
        Employee anil = new Employee(40, "Anil");

        employees.add(arun);
        employees.add(ankit);
        employees.add(jon);
        employees.add(anil);

        for (Employee employee : employees) {
            int id = employee.getId();
            String name = employee.getName();

            System.out.println("id : "+id +" name : "+name);
        }
    }

}

Upvotes: 1

Sdyess
Sdyess

Reputation: 340

ArrayList works in the sense of [index, element].

By using the get method, you're using index as the parameter and it returns the element at that position. So if you're accessing the element by it's index you already have both the id and element, but a different collection interface might suit you better like a map.

http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

Upvotes: 1

Related Questions