Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is one of my class
class number11 {
String ab;
int i;
public number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
}
And in main method, I used
List<number11> n1= new ArrayList<number11>();
How can I access the value of integers and String contained in List? I do wish just to print them but to use further.
{Closed ,Thank you all}
Just loop over the list:
for (number11 n : list) {
String ab = n.ab;
int i = n.i;
//print ab and i
}
Note that number11 should be in CamelCase to follow Java's conventions: Number11.
From your question it seems you want list of your objects,
Before continuing, please create getters and setters, I've used them
Also your class name should be camelCase. Number11 is valid but not number11
You can fill the list using
List<number11> list = new ArrayList<number11>();
list.add(new number11("a",1));
list.add(new number11("b",2));
To access the members,
for (number11 n : list) {
String ab = n.getAb();
int i = n.getI();
}
like this
List<number11> n1= new ArrayList<number11>();
for(number11 n:n1){
System.out.println("String value: "+n.ab);
System.out.println("int value: "+n.i);
}
According to better coding standards.Follow the below rules
1.Change you class so that It starts with a camel case.
2.Change variables to private.
3.Add setter and getter methods
Assuming you have added values to the ArrayList you can read values by using code such as n1.get(0).ab or n1.get(0).i.
List l = new ArrayList<number11>();
l.add(new number11("x",1));
l.add(new number11("y",2));
for (number11 element : l) {
System.out.println(element.ab + " "+ element.i);
}
You might first want to add getter methods to your class number11.
e.g
public class number11{
String ab;
int i;
public number11(String ab,int i)
{
this.ab=ab;
this.i=i;
}
public int getI(){
return i;
}
public String getAb(){
return ab;
}
}
You need to obtain a reference to the particular object held inside the ArrayList via the get(index) method where index is the element number starting with 0. Simply call the getter methods to retrieve the values.
e.g
List<number11> n1= new ArrayList<number11>();
//Adding the object
n1.add(new number11("Test", 4));
//Retrieving the object.
number11 inst = n1.get(0);
//Retrieve and print the values
System.out.println(inst.getAb());
System.out.println(inst.getI());
For better convention change your class structure to,
class Number11 {
private String ab;
private int i;
public Number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Access in this way.
List<number11> n1= new ArrayList<number11>();
if(n1!=null && n1.size()>0){
for (Number11 n : n1) {
String ab = n.getAb();
int i = n.getI();
//print ab and i
}
}
List<number11> n1= new ArrayList<number11>();
after adding values to this list n1 it will contains number11 type objects from index 0 to n-1, where n is number of element you added to list.
Then you can call what ever object as follows
n1.get(1) // this will return 2nd object in the list
It will contain ab and i
You can call them as follows
n1.get(1).getab // 2nd element ab value in list n1
n1.get(1).i // 2nd element i value in list n1
List Interface allows to:
Positional access — manipulates elements based on their numerical position in the list
MyClass obj = myList.get(24); //--get 25th item of a List<MyClass>--
Iteration access — extends Iterator semantics to take advantage of the list's sequential nature
for(MyClass obj : myList){ //-- go through all items of a List<MyClass> one by one--
int i = obj.someField;
}
Once you have your object, you can access its fields.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My problem is I need to make a program where you can search for an employee based on their ID number. Which needs to be something like "E1" or "E2". I am struggling to find a way to search for numbers and letters in the same object. It only works when I use just a number like 1 or 2 by using Int.
How can I store both a letter and integer in an object? Is there something similar to String that stores letters or Int that stores numbers but for both letters and numbers?
Ex. I can search for my employe already but their ID is currently just "1" or "2" or "3". I need to change it to "E1" or "E2" etc. But it wont work with String or Int.
I am searching an array. In an employee class
You can check, if two Strings are equal, by using the equals method: String1.equals(String2);
Also, you could implement a new class implementing the interface Comparable. In this class you could split the ID into a String and an Integer part:
public class EmployeeID implements Comparable {
String s = null;
Integer i = null;
public EmployeeID(String s, Integer i) {
this.s = s;
this.i = i;
}
#Override
public void equals(EmployeeID id) {
return new String(s + i).equals(new String(id.s + id.i));
}
#Override
public void compareTo(EmployeeID id) {
return new String(s + i).compareTo(new String(id.s + id.i));
}
}
Of course, if you do not need to compare elements (which can be useful for sorting), you can just implement this wrapper class without the comparable interface.
The equals method compares two ids and is not implemented in the Comparable interface, but the Object class, which is the superclass of every class.
No code provided so I'm guessing as to what you actually are trying to do.
public class SomeIds {
private String[] ids;
public boolean isPresent(String id) {
for (String element : ids) {
if (element.equals(id)) {
return true;
}
}
return false;
}
/**
* returns the index of the first element matching the id
* provided or -1 if it is not found
*/
public int indexOf(String id) {
for (int index = 0 ; index < ids.length ; ++index) {
if (ids[index].equals(id)) {
return index;
}
}
return -1;
}
}
Unfortunately, you won't be able to mix types (i.e. numbers and letters). You'll have to use a String for storage of the ID, in which case, you can use equals to search:
String searchTerm = "E1";
for (Employee employe : employeeArr) {
if (employe.getId() == searchTerm) {
System.out.println("Employe_ID: E" + employe.getEmployeId() +
"\narbetstitel: " + employe.getArbetsTitel());
}
}
Better yet, use a HashMap so you don't have to loop to find an employee:
HashMap<String, Employee> employees = new HashMap<>(); // String to store IDs
Employee e = new Employee();
employees.put("E1", e);
// To fetch an employee
Employee e1 = employees.get("E1");
if (e1 != null) {
System.out.println("Employe_ID: E" + e1.getEmployeId() +
"\narbetstitel: " + e1.getArbetsTitel());
}
I'm new to Java and I'm trying to get my head around constructs, classes and objects. I apologise if any of this seems stupid to you.
I have been tasked with creating an ArrayList to hold items of type Data (my class). using the .add method - I should add a certain number of names and ages then output.
I have sort of done it, but I was wondering if I could use the functions like SetAge and SetAge from my class to use within my ArrayList to create a new person and then output it together like I have with the rest. Is there another way?
Thank you for your help & explanation.
Below is my code;
import java.util.ArrayList;
public class workingOn {
public static void main (String[] args)
{
Data Fred = new Data("Fred", 21);
Data Jo = new Data("Jo", 43);
Data Zoe = new Data("Zoe", 37);
ArrayList<Data> myArray = new ArrayList<Data>();
myArray.add(Fred);
myArray.add(Jo);
myArray.add(Zoe);
for (Data temp : myArray)
{
System.out.println(temp.toString());
}
}
}
Below is my class;
public class Data {
private String name;
private int age;
Data(String n,int a)
{
name = n;
age = a;
}
public String GetName()
{
return(name);
}
public void SetName(String n)
{
name = n;
}
public int GetAge()
{
return(age);
}
public void SetAge(int a)
{
age = a;
}
public void Print()
{
System.out.print(("("+ GetName() ));
System.out.print(",");
System.out.print(GetAge());
System.out.print(") ");
}
//i made this so I don't output the object id
public String toString() {
return (name + ", " + age);
}
}
Going through the comments, I am guessing you want to somehow use the setter methods (setName() and setAge()) for the class that you have designed. The easiest way would be:
Data d = new Data("tempName", 10);
myArray.add(d);
This basically creates an object of type Data and adds it to the arraylist. Let's assume that you want to change the name and age of this person you just added, then you should do this:
myArray.get(myArray.size() - 1).setName("newName");
myArray.get(myArray.size() - 1).setAge(18);
To add some explanation, when you add an object to an arraylist, it always adds in the end. We use size() method to get the number of objects in the Arraylist. Since index starts from 0, we use myArray.size() - 1. We use the .get() method to retrieve the object from the arraylist which takes a number as a parameter and return the object at that index.
Combining these two, we get the object at the last possible index, and call the setName() and setAge() function on it.
Hope this helps.
I know you can add objects to an arraylist at a specified index but I was wondering what happens to the indices before, after and between the objects placed at these indexes.
I am implementing an exam grading system and I have a Student getAnswers() method that retrieves all the answers provided by a student on an exam. I store it in an arrayList.
ArrayList<Answer> studentAnswers = new ArrayList<Answer>();
Now every answer knows the question number it corresponds to so within this arraylist i'd like to add the answers to the index specified by the questionNumber.
for(Answer s: getAnswers()){
studentAnswer.set(s.getQuestionNumber(), s);
}
My issue is that if the student didn't answer one of the questions, I want it to be a null answer. I don't know if this is the right way to handle that.
An example would be:
StudentAnswer [question 1, "Foo"]
StudentAnswer [question 2, "Class"]
StudentAnswer [question 4, "Object"]
And if the answer key was ["Foo", "Class", "Interface", "Object"]
The studentAnswers list should look like this: ["Foo", "Class", Null, "Object"]
Null because he didn't answer question 3.
I don't know if this is the right way to handle that.
I feel like an array rather than ArrayList would be better suited for this problem since you'll need to initialize the size of the array with your number of questions.
import java.util.Arrays;
class StudentAnswer {
private int id;
private String value;
public StudentAnswer(int id, String ans) {
this.id = id;
this.value = ans;
}
public int getQuestionNumber() {
return this.id;
}
public String toString() {
return this.value;
}
}
class Main {
public static void main(String[] args) {
StudentAnswer a0 = new StudentAnswer(0, "Foo");
StudentAnswer a1 = new StudentAnswer(1, "Class");
StudentAnswer a3 = new StudentAnswer(3, "Object");
int totalQuestions = 4;
StudentAnswer[] answers = new StudentAnswer[totalQuestions];
answers[a0.getQuestionNumber()] = a0;
answers[a1.getQuestionNumber()] = a1;
answers[a3.getQuestionNumber()] = a3;
System.out.println(Arrays.asList(answers));
}
}
Output
[Foo, Class, null, Object]
Note: The quotes won't display on the strings unless you modify the toString method in StudentAnswer.
I have a class that called Entries that holds my constructor along with its getters and setters.
In a new class, I have :
private LinkedList<Entry>[] Entries = new LinkedList[26];
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}
However, I am receiving errors for my setters and getters. This does not happen when I use a straight array or straight LinkedList, as I've already got this method working for those two in two different classes.
The error messages I'm receiving for both are
The method getNumber() is undefined for the type LinkedList
and The method getNumber() is undefined for the type LinkedList
I don't see why they're undefined as when I've tried doing the same method for a straight Array and a pure LinkedList, they've handled it fine and functioned properly.
If anyone has any suggestions, I would really appreciate it.
Pay close attention to the data type you're iterating over. Because myEntries is defined as a LinkedList<Entry>[], you're pulling out an individual LinkedList<Entry> when you iterate over the array.
It really seems like you don't want the array; instead, just iterate over the list elements directly:
LinkedList<Entry> myEntries = new LinkedList<>();
for(Entry entry : myEntries) {
if(entry.equals(number) {
// logic
}
}
myEntries[i] returns a LinkedList this doesnt have the setNumber method. You need to get the Entry out of the list and then invoke these methods.
myEntries[i].get(index).setNumber(); or myEntries[i].getFirst().setNumber(); etc
You are trying to call your accessors/mutators (getNumber() & setNumber) on the LinkedList instance and since there is no such methods for the LinkedList you will have the reported error.
So either get access to some LinkedList item with get() method that will return an Entry object on which you can call your setter and getter:
public void changeNumber(String number, String numberChange) {
int index = 0; //not sure what this index should be in your case
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].get(index).getNumber().equals(number)){
myEntries[i].get(index).setNumber(numberChange);
break;
}
}
}
Or better if you don't need the LinkedList, may be it is worth dropping you design and only create an Array of Entry:
private Entry[] entries = new Entry[26];
Then your changeNumber() method will be eligible:
public void changeNumber(String number, String numberChange) {
for (int i = 0; i < myEntries.length; i++){
if (myEntries[i].getNumber().equals(number)){
myEntries[i].setNumber(numberChange);
break;
}
}
}
I have two Collection objects, I want to associate each object of these two in a readable way (HashMap, Object created on purpose, you choose).
I was thinking of two loops one nested into the other, but maybe it's a well known problem and has a commonly understandable solution...
What if the number of Collection objects raises above two?
EDIT after Joseph Daigle comment: The items of the Collection objects are all of the same type, they are rooms of hotels found to be bookable under certain conditions.
Collection<Room> roomsFromA = getRoomsFromA();
Collection<Room> roomsFromB = getRoomsFromB();
for(Room roomA : roomsFromA){
for(Room roomB : roomsFromB){
//add roomA and roomB to something, this is not important for what I need
//the important part is how you handle the part before
//especially if Collection objects number grows beyond two
}
}
EDIT 2: I'll try to explain better, sorry for the question being unclear.
Follows an example:
A user requests for a double and a single room.
The hotel has 3 double and 4 single rooms available.
I need to associate every "double room" to every "single room", this is because each Room has its own peculiarity say internet, a more pleasant view, and so on. So i need to give the user all the combinations to let him choose.
This is the simple case, in which only two Collection of Room objects are involved, how do you manage the problem when say both hotel and user can offer / request more Room types?
What you are trying to do here is to get all possible permutations of choosing X from a set of Y. This is a well known problem in discrete mathematics and I think it is just called Combinatorial Mathematics.
To solve your problem you need to create a super collection containing all your Room types. If this is an array or a List you can then use this example to calculate all possible ways of choosing X from the set of Y. The example will give you the indices from the list/array.
Do the collections line up exactly?
HashMap map = new HashMap();
for (int i=0; i<c1.Size(); i++) {
map.put(c1[i], c2[i]);
}
Well, since I don't know if you will need to search for both of them having only one, the HashMap won't work.
I would create a class that receives a Pair.. sort of:
private static class Pair<K, T> {
private K one;
private T two;
public Pair(K one, T two) {
this.one = one;
this.two = two;
}
/**
* #return the one
*/
public K getOne() {
return one;
}
/**
* #return the two
*/
public T getTwo() {
return two;
}
}
And create a List with them.
Your example implies that the return value from "roomsFromB" is a subcollection of the return value of "roomsFromA", so it'd be more natural to model it that way:
class Room {
public Collection<Room> getRoomsFromB { ...
}
which would then let you do :
//Collection rooms
for (Room a: rooms)
{
for(Room b a.getRoomsFromB){ ...
This is assuming that they're modeled hierarchically, of course. If they're not then this is inappropriate, but then the question you're asking, it seems to me, is really how to model the relationship between them, and you haven't yet made that explicit.
You might reconsider whether you need exactly this logic. You're introducing an O(n^2) operation, which can quickly get out of hand. (Technically O(mn), but I'm guessing m and n are roughly the same order.)
Is there another solution to your problem? Perhaps you could create a 'set' which includes all of A and all of B, and then each object in A and B could point to this set, instead?
I assume that:
Each element in collection 1 will
match a single element in
collection 2
The collections have the same
size
The collections can be ordered and
the order matches each element in
both collections
Order both collections (in the same
order) by the property that
identifies each object.
Iterate through both collections with a single loop, build a relation object and add it into a new collection.
See if this helps you:
public static class Room {
private int number;
private String name;
public Room(int number, String name) {
super();
this.number = number;
this.name = name;
}
public int getNumber() {
return number;
}
public String getName() {
return name;
}
}
public static class RoomRelation {
private Room a;
private Room b;
public RoomRelation(Room a, Room b) {
super();
this.a = a;
this.b = b;
}
public Room getA() {
return a;
}
public Room getB() {
return b;
}
#Override
public String toString() {
return a.getName() + "(" + a.getNumber() + ") " + b.getName() + "(" + b.getNumber() + ")";
}
}
public static void main(String[] args) {
List<Room> roomsFromA = new ArrayList<Room>();
List<Room> roomsFromB = new ArrayList<Room>();
roomsFromA.add(new Room(1,"Room A"));
roomsFromA.add(new Room(2,"Room A"));
roomsFromB.add(new Room(1,"Room B"));
roomsFromB.add(new Room(2,"Room B"));
Comparator<Room> c = new Comparator<Room>() {
#Override
public int compare(Room o1, Room o2) {
return o1.getNumber() - o2.getNumber();
} };
Collections.sort(roomsFromA, c);
Collections.sort(roomsFromB, c);
List<RoomRelation> relations = new ArrayList<RoomRelation>();
for (int i = 0; i < roomsFromA.size(); i++) {
relations.add(new RoomRelation(roomsFromA.get(i), roomsFromB.get(i)));
}
for (RoomRelation roomRelation : relations) {
System.out.println(roomRelation);
}
}
Your question is quite unclear. As I understand you want to list all combinations of rooms, minus duplicates. Here us some code to build up a 2d array of all the room combinations. For more kinds of room, put in another nested loop.
Collection<Room> roomsFromA = getRoomsFromA();
Collection<Room> roomsFromB = getRoomsFromB();
Room[][] combinations = new Room[roomsFromA .size()][roomsFromB .size()];
int a = 0;
int b = 0;
for(Room roomA : roomsFromA){
for(Room roomB : roomsFromB){
combinations [a][b] = [roomA][roomB]; //Build up array
b++;
}
a++;
}
return combinations;
It is a common problem. It's called a Cartesian product. If you have two collections like in your case, I would not hesitate to have two nested loops. Otherwise, see this question.