I have a class called anItem and it allows me to model variables into an object.
I have many of these objects and i want to put them into a colection. What is the class code for the collection?
Here is what i have:
package com.rest.myproject;
public class anItem
{
String name;
String age;
public anItem()
{
super();
}
//methods
public String getName()
{
return this.name;
}
public void setName(String newName)
{
this.name=newName;
}
public String getAge()
{
return this.age;
}
public void setAge(String newAge)
{
this.age=newAge;
}
}
Public class aCollectionOfItems
{
anItem[] item; ->should I create a array of items to add and remove from?
public aCollection()
{
super();
}
//How do I add aItem to my collection, create an array of items?
}
Use a List to hold your items.
public class Item {
private String name;
private String age;
//methods
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return this.age;
}
public void setAge(String age) {
this.age = age;
}
}
public class CollectionOfItems {
List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
}
public class CollectionOfItems {
int size = 10; //any size that is required.
private final Item[] item;
public aCollection(){
super();
item = new Item[size];
}
}
Java Collections can also be used to hold the items, as a replacement for Arrays.
I suggest on reading through Oracle's documentation / tutorial of Java collections:
https://docs.oracle.com/javase/tutorial/collections/
A few brief examples:
ArrayList - This is a list of objects, stored as an array.
Useful form quick ransom access
LinkedList - This is also a list. Useful if you don't know the size of the list ahead of time, but it's
not efficient for random access
HashSet - This is a set. Only one of each items is allowed. Items are compared using hashCode() and equals().
TreeSet - This is also a set. Items are sorted, so you can
iterate them in some order.
HashMap - This is a key/value collection.
For example HashMap is will store/retrieve
TreeMap - This is also key/value store. Items are sorted.
Related
I think it's normal desire to have access for manipulating with data. Should i create getters/setters in Record class, if i already use Storage for this goal, made on Record? Or what need to do?
public class Storage {
List<Record> record;
public Storage(){
this.record = new ArrayList<Record>();
}
public void addRecord(Record record) {
this.record.add(record);
}
public Record getRecord(int number){
return this.record.get(number);
}
public class Record {
private int number;
private int count;
private Object code;
/* public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
} */
public Record(int number, int count, Object code) {
this.number = number;
this.count = count;
this.code = code;
}
#Override
public String toString() {
return (this.number+" "+this.code+" "+ this.count);
}
}
According to me it is not require to write setter and getter methods until you don't want to modify them.In your code you have initialized fields in constructor and overridden toString() method to get meaningful content of Record object and never trying to modify Record 's fields directly.
I strongly feel that it is not required.
Actually I want to sort Array List of objects. I am using Comparable interface for this purpose. It is completely working But the problem is that when I am sorting is is giving these two problems.
All name who have 1st letter capital are coming together on the top and all name who have 1st letter small are coming together on the bottom.
All the sorted Capital letters word are coming together after that all the small letter words are coming at bottom together.
Here is my bean
MyShares.java
public class Myshares implements Comparable<Myshares> {
int id, parent;
String name, path, type, shared_with, shared_or_not, upload_request;
public int getParent() {
return parent;
}
public void setParent(int parent) {
this.parent = parent;
}
public String getUpload_request() {
return upload_request;
}
public void setUpload_request(String upload_request) {
this.upload_request = upload_request;
}
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;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getShared_with() {
return shared_with;
}
public void setShared_with(String shared_with) {
this.shared_with = shared_with;
}
public String getShared_or_not() {
return shared_or_not;
}
public void setShared_or_not(String shared_or_not) {
this.shared_or_not = shared_or_not;
}
#Override
public int compareTo(Myshares another) {
return this.name.compareTo(another.getName());
}
}
This is the output
I think it is based on ASCII code. I want a complete sorted list. Please take a look.
If you are wishing for a case-insensitive sort, I would recommend changing your compareTo() method to instead use the compareToIgnoreCase() method of String - namely:
public int compareTo(Myshares another) {
return this.name.compareToIgnoreCase(another.getName());
}
Change
#Override
public int compareTo(Myshares another) {
return this.name.compareTo(another.getName());
}
to
#Override
public int compareTo(Myshares another) {
return String.CASE_INSENSITIVE_ORDER.compare(this.name, another.getName());
}
or use the more readable and also very good solution posted by nullPainter.
you should adjust your compareTo() method
return this.name.toLowerCase().compareTo(another.getName().toLowerCase());
Replace the compareTo method with:
public int compareTo(Myshares another) {
return this.name.compareToIgnoreCase(another.getName());
}
I gave you some source to an existing Comparator I wrote which does full Alpha Numeric sorting and will work with numbers in the names like 10, 1, etc
To use it you can do: Collections.sort(myList, comparator);
An alternative would also be in your compare method to lowercase both sides. But anytime you have numbers or symbols it will be thrown off so I would personally use the Comparator.
Checkout the GIST with the source code at: https://gist.github.com/gondor/9328de5fa0cce130bc3b
I have been set an assignment to create a small register based program written in Java, in the form of a linked list. I started by creating a student class, and then a tester file for the class. Following that, in the registry file I have set out my methods, and a constructor, and am in the process of writing a tester file to test all my methods.
However I am having trouble when trying to remove a specific element from my linkedlist, I want to be able to remove a student, referencing them by their individual studentID, but am not sure how to do this.
Whilst trying to solve the problem I came across the removeFirstOccurrence(Object o) method. Is this the right method to use?
Any help would be much appreciated.
STUDENT FILE CODE:
public class Student {
private String foreName;
private String surName;
private int studentID;
//declaring the variables needed for my student
public Student (String foreName, String surName, int studentID)
{
this.foreName = foreName;
this.surName = surName;
this.studentID = studentID;
}
//constructor to set out what a student needs
public String getForeName() {
return foreName;
}
public String getSurName() {
return surName;
}
public int getStudentID() {
return studentID;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
// getters and setters for my variables
public String toString ()
{
return getClass().getName() + "foreName = " + foreName + "surName = " + surName + "studentID = " + studentID;
}
//my toString method
}
REGISTRY FILE CODE:
import java.util.*;
public class Registry {
LinkedList<String> studentList
= new LinkedList<String>();
//setting my type parameter
public Registry() {}
//empty constructor to hold arguements
public void addStudent(String aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(int studentID)
{
//????
}
#Override public String toString()
{
return "Registry";
}
public String format()
{
}
REGISTRY TESTER FILE CODE:
import java.util.*;
public class RegistryTester {
public static void main (String[] args)
{
LinkedList<String> studentList
= new LinkedList<String>();
System.out.println("Test 1");
System.out.println("Methods tested: addStudent, constructor");
System.out.println("********************");
studentList.add("Joe Perkins 123");
studentList.addLast("Shilpa Gupta 1234");
studentList.addLast("Seany Ray 12345");
// adding 3 students to my list
System.out.println(studentList);
}
}
Define the List as a List of Student
LinkedList<Student> studentList = new LinkedList<Student>();
Override the hashCode() and equals() method in Student class.
public boolean equals(Object obj) {
if (obj instanceof Student) {
return studentID == ((Student)obj).getStudentID();
}
return false;
}
public int hashCode() {
return studentID;
}
Define methods:
public void addStudent(Student aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(Student astudent)
{
this.studentList.remove(aStudent)
}
First you should make your LinkedList for type Student:
LinkedList<Student>
Then to remove a student, you could :
go through the list, find out the student object with same id, remove it
override equals() and hashcode() method in your Student class, then
public void deleteStudent(int studentID)
{
//getStudent object (stu) By the given ID
studentList.remove(stu);
}
use Map, (HashMap or LinkedHashMap) instead of LinkedList, key is the studentId, value is the studentObject. This will make add/remove easier.
If you have a Collection (in your case a LinkedList) of Students and call remove(studentToRemove) on it, Java will compare each object with studentToRemove by using its equals() method.
In your case, you haven't written an equals() method, hence the one for Object is used. If indeed a student is uniquely identified by its studentId (that is, two Student instances with the same studentId are always the same student) you should override the equals() metod and check for equality using that field.
Read about equals() and hashCode().
Another alternative would be to iterate the list until you find the match, and then remove the student from the list.
I have class ABC
class ABC{
private List<XYZ> xyzList -- Though its list it contains single object;
private String txt;
}
class XYZ{
private long price;
}
I want to sort List abcList based on class XYZ price variable.
Please provide best possible approach for sorting in ascending order.
Have you tried one of these methods:
java.util.Collections.sort(List<T>)
Or
java.util.Collections.sort(List<T>, Comparator<? super T>)
One way is implement Comparable interface in XYZ and override compareTo and then Collections.sort(yourListOfXYZ) will sort the list.
Other way is using Comparator.
Collections.sort(xyzList, new Comparator<XYZ>() {
#Override
public int compare( XYZ e1,XYZ e2) {
return Long.valueOf(e1.getPrice()).compareTo(Long.valueOf(e2.getPrice()));
}
});
Try this
Collections.sort(xyzList);
I would suggest you look into the documentation for the Comparable interface. Possible even with the use of an PriorityQueue.
In you case you either need to make XYZ implement Comparable, provide a Comparator<XYZ> or a simpler option is to unwrap it and just use a List<Double> or a SortedSet<Double> to hold you prices.
Sample code from http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/
public class MyArrayListSort {
public static void main(String a[]){
List<Empl> list = new ArrayList<Empl>();
list.add(new Empl("Ram",3000));
list.add(new Empl("John",6000));
list.add(new Empl("Crish",2000));
list.add(new Empl("Tom",2400));
Collections.sort(list,new MySalaryComp());
System.out.println("Sorted list entries: ");
for(Empl e:list){
System.out.println(e);
}
}
}
class MySalaryComp implements Comparator<Empl>{
#Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}
I have this class:
public class Friend {
private String name;
private String location;
private String temp;
private String humidity;
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
I want to sort a List based on name, location, temp and humidity based on user input.
EDIT:The user specifies by which data member the sorting has to be done.
What is the easiest way to do this?
Thank you.
Because you want to sort them by four different standards, implementing Comparable does not make sense. In this case, you may find that creating different Comparators for each sort-by parameter. However, you could implement Comparable for the most logical sort-by field, such as name. Otherwise, comparators are the way to go.
public class FriendNameComparator extends Comparator<Friend> {
// assuming both are non-null for code simplicity; you may wish to change that
public int compare(Friend f1, Friend f2) {
return f1.getName().compareTo(f2.getName());
}
}
public class FriendLocationComparator extends Comparator<Friend> {
// assuming both are non-null for code simplicity; you may wish to change that
public int compare(Friend f1, Friend f2) {
return f1.getLocation().compareTo(f2.getLocation());
}
}
// and so forth
Then, you can use the sort function of the Collections utility class to sort by the given comparator.
Collections.sort(friendsList, new FriendNameComparator()); // sorts by name
Collections.sort(friendsList, new FriendLocationComparator()); // sorts by location
// etc
Java has a static function called Collections.sort(List, Comparator) which sorts a (generified) List of objects given a custom Comparator which, given two objects of the same type, determines which one is ordered before the other.
Your task is to write a function which creates a Comparator which orders the objects based on its arguments and the user specified sort order. For example:
public Comparator<Friend> getComparator(final String sortBy) {
if ("name".equals(sortBy)) {
return new Comparator<Friend>() {
#Override int compare(Friend f1, Friend f2)
return f1.getName().compareTo(f2.getName());
}
};
} else if ("location".equals(sortBy)) {
return new Comparator<Friend>() {
#Override int compare(Friend f1, Friend f2)
return f1.getLocation().compareTo(f2.getLocation());
}
};
} else if ("temp".equals(sortBy)) {
// ...
} else {
throw new IllegalArgumentException("invalid sort field '" + sortBy + "'");
}
}
List list=new ArrayList();
Use If else if for each criteria:
if(location ){
Collections.sort(list, new Comparator () {
public int compare(YourObject o1, YourObject o2) {
return o1.getLocation().compareTo(o2.getLocation());
}
});
}
} else if(temp ){
........
}
.......