how to make a connected list of elements in Java - java

i want to make a connected list of Student elements. The class Student must have only two fields(name and codeNumber).I also created a method to compare the names and if the names are equals then i compare codeNumbers. this is because i must insert the elements low to high.
I created a class like:
class Student
private String name;
private int codeNumber;
public Student(String name, int AM){
this.name = name;
this.codeNumber = codeNumber;
}
public int compareTo(Student other){
int result;
if(other.name.compareTo(this.name) == 0){
result = 0;
return result;
}
if(other.name.compareTo(this.name) < 0){
result = 1;
return result;
}
if(other.name.compareTo(this.name) > 0){
result = -1;
return result;
}
if(other.codeNumber > this.codeNumber){
result = 1;
return result;
}
if(other.codeNumber < this.codeNumber){
result = -1;
return result;
}
}
public String getName(){
return name;
}
public int getcodeNumber(){
return codeNumber;
}
}
And here is the problem. I need a StudentList class to make my own list.
So i created the class but im not sure if i have the right fields in this class.
I created 4 fields:
1.private Student studentElement;
2.private StudentList next = null; a reference to the next element
3.private StudenList head; a reference to the start of the list
4.private int size = 0; to know the number of the elements
And here is my code:
class StudentList{
private Student studentElement;
private StudentList next = null;
private StudentList head;
private int size = 0;
public StudentList(Student listEl){
listElement = listEl;
}
public boolean containsElement(Student p){
StudentList position = head;
while(position != null){
if(StudentElement.getName().equals(p.getName()) && studentElement.getAM() == p.getAM()){
return true;
}
position = position.getNext();
}
return false;
}
}
This is my code. Can anyone tell me if i have the right types of fields in my class and help me creating an insert method.

Don't reinvent the wheel.
Prefer using java.util.LinkedList
and add the Student instances in the way you need. This will preserve the order in
which you add to the list

Use one of the Java library list implementations such as ArrayList or LinkedList which do precisely what you want, no point in rolling-your-own.
Also learn about Collections.sort() if needed.
Your Student class should also implement the Comparable interface which (by a stroke of luck) has the same signature as your existing compareTo method.

Related

Use iterator to check an ascending order (row major order) arraylist of a specific object with a number id?

I have a class that implement an iterator, each object in this class has an id which refers a number.
public class Shelf extends Observable implements Iterable<Book>{
final static int NumRow = 10;
final static int NumCol = 10;
Book[][] books = new Book[NumRow][NumCol];
# Here is the code for Iterator<Book> iterator();
I have already implement the iterator with hasNext, and Next methods
class Book implement Comparable<Book>{
private int id
public int getId() {return id;}
How can I check if the entire arraylist is in ascending order by each object's id?
This is what I wrote
boolean ascending order(){
boolean check = true;
Iterator<Book> iter = shelf.iterator();
while (iter.hasNext()){ \\How can I wrote here?
}
return check;
How can I compare the current id with the next id?
You can try the following code.
public boolean checkAscendingSort(List<Book> books){
for(int i=1; i<books.size(); i++){
if(books.get(i).getId() < books.get(i-1).getId()){
return false;
}
}
return true;
}
You can store the value of the id and check at the next element, then change the value of previous
private static boolean isOrdered() {
Iterator<Book> ite = shelf.iterator();
int previousId = Integer.MIN_VALUE;
while (ite.hasNext()) {
Book next = ite.next();
if (next.getId() < previousId) {
return false;
}
previousId = next.getId();
}
return true;
}

How do I search an ArrayList of Objects

I am creating an ArrayList of Accounts (an object) and the Account constructor is
public Account(String name, int accNum, int balance)
{
myName = name;
myAccountNum = accNum;
myBalance = balance;
}
I want to know how to check the ArrayList to determine if a given accountNumber exists in it, and if it does, return true
private static ArrayList<Account> accounts = new ArrayList<Account>();
My initial thought was this, but I do not think that this works
if(accounts.contains(tempAccNum))
{
//executes code that I have
}
For the Java ArrayList, contains performs an object equality comparison. To use .contains, you would need to
Implement the .equals() method for the Account class, and have it check only the this.myAccountNum property against the account number of the input Account.
Create a dummy Account with the desired account number to pass into contains.
A better method would involve evaluating an iterator, and checking the account numbers at each step. Here I assume that myAccountNum is a public property of the Account class.
Iterator<E> it = Accounts.iterator();
while (it.hasNext()) {
Account acc = it.next();
if(acc.myAccountNum == tempAccNum)
return true;
}
For ArrayList specifically, using .get with an index is not too bad:
for(int index = 0; index < Accounts.size(); ++index) {
if(Accounts.get(index).myAccountNum == tempAccNum)
return true;
For other List types, using indices can be very poor.
Ways to iterate over a list in Java
I will suggest you to make it simple by just implementing an equals() method for account class.
#Override
public boolean equals(Object o){
if(o==null)return false;
if(o.getClass()!=this.getClass())return false;
Account demo = (Account)o;
if(!demo.myName.equals(this.myName))return false;
if(demo.myAccountNum != this.myAccountNum)return false ;
if(demo.myBalance = this.myBalance)return false ;
}
then use contains method
First add getter for accNum in Account model
Then try this
public boolean containsAcc(int accno) {
for(int i=0;i<accounts.size();i++) {
if(accounts!= null && accounts.get(i).getMyAccountNum()==acno) {
return true;
}
}
return false;
}
Here getMyAccountNum() is the getter declared in Account model(shown below)
Then check this
if(containsAcc(tempAccNum))
{
//your code
}
Your Account model should be like this
public class Account {
String myName;
int myAccountNum;
int myBalance;
public Account(String name, int accNum, int balance)
{
this.myName = name;
this.myAccountNum = accNum;
this.myBalance = balance;
}
public int getMyAccountNum() {
return myAccountNum;
}
}

Removing Duplicate Entries in Array - Java

For Java practice, I am trying to create a method inside my EmployeesDirectory Class that:
Removes Duplicate entries from the array
The array should be the same length after removing duplicates
Non-Empty entries should be making a contiguous sequence at the beginning of the array - and the actualNum should keep a record of the entries
Duplicate Means: Same Name, Position and Salary
Here is my Current Code:
I am unsure on how to implement this - any help would be appreciated
class EmployeeDirectory {
private Employee dir[];
private int size;
private int actualNum;
public EmployeeDirectory(int n) {
this.size = n;
dir = new Employee[size];
}
public boolean add(String name, String position, double salary) {
if (dir[size-1] != null) {
dir[actualNum] = new Employee(name, position, salary);
actualNum++;
return true;
} else {
return false;
}
}
}
I'd rather you did not write a distinct method for removing duplicates. If I were you, I would search for duplicates in add method and then instantly decide whether I need to add Employee.
Also, why don't you use Sets (link for HashSet) instead of arrays for your purpose? Sets by their own definition disallow adding duplicates, so they seem to be appropriate as a solution
First of all, Override equals and hashCode methods in Employee class as follow
#Override
public boolean equals(Object other) {
if(this == other) return true;
if(other == null || (this.getClass() != other.getClass())){
return false;
}
Employee guest = (Employee) other;
return Objects.equals(guest.name, name)
&& Objects.equals(guest.position, position)
&& Objects.equals(guest.salary, salary);
}
#Override
public int hashCode() {
return Arrays.hashCode(new Object[] {
name,
position,
salary
});
}
Then you can use Stream API distinct method to remove duplicates
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream.
You can do it like so
Employee e1 = new Employee("John", "developer", 2000);
Employee e2 = new Employee("John", "developer", 2000);
Employee e3 = new Employee("Fres", "designer", 1500);
Employee[] allEmployees = new Employee[100];
allEmployees[0] = e1;
allEmployees[1] = e2;
allEmployees[2] = e3;
allEmployees = Arrays.asList(allEmployees).stream().distinct()
.toArray(Employee[]::new);
Arrays.asList(allEmployees).forEach(System.out::println);
Output: (keeping both empty and non-empty entries)
John developer 2000.0
Fres designer 1500.0
null
Unfortunately, I have not got the Employee class to verify my code, but try this:
void removeDuplicates() {
int length = dir.length;
HashSet set = new HashSet(Arrays.asList(dir));
dir = new Employee[length];
Employee[] temp = (Employee[]) set.toArray();
for (int index = 0; index < temp.length; index++)
dir[index] = temp[index];
}
The code must remain the size of array after deletion the duplicates. At the beginning of array there must be valid Employees, at the end - nulls.
And don't forget to add this at the beginning of your .java file
import java.util.Arrays;
import java.util.HashSet;
If your task states as "remove duplicates from array" (i. e. you cannot use ArrayList or control when adding items), you can use the following approach:
public void removeDuplicates() {
Set<Employee> d = new HashSet<>(); // here to store distinct items
int shift = 0;
for (int i = 0; i > dir.length; i++) {
if (d.contains(dir[i])) { // duplicate, shift += 1
shift++;
} else { // distinct
d.add(dir[i]); // copy to `d` set
dir[i - shift] = dir[i]; // move item left
}
}
for (int i = d.size(); i < dir.length; i++)
dir[i] = null; // fill rest of array with nulls
actualNum = d.size();
}
Here, shift variable stores number of duplicates found in the array so far. Every distinct item is moved to shift positions left in order to make sequence continuous while keeping initial ordering. Then remaining items are altered to nulls.
To make hash-based collections work with Employee instances correctly, you also need to override hashCode() and equals() methods as follows:
public class Employee {
//...
#Override
public int hashCode() {
return Objects.hash(name, position, salary);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (!o.getType().equals(this.getType()) return false;
Employee e = (Employee) o;
return Objects.equals(e.name, name)
&& Objects.equals(e.position, position)
&& Objects.equals(e.salary, salary); // or e.salary == salary, if it primitive type
}
}

Compare arraylist objects in java

I have list of objects in an arraylist and I need to compare every objects with other objects available in the arraylist;
For Example:
Class Employee {
private String empname;
private Long empid;
private boolean empsex;
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Long getEmpid() {
return empid;
}
public void setEmpid(Long empid) {
this.empid = empid;
}
public boolean isEmpsex() {
return empsex;
}
public void setEmpsex(boolean empsex) {
this.empsex = empsex;
}
}
public list<Employee> getEmpList() {
List<Employee> empList = new ArrayList<Employee>();
Employee emp = new Employee();
for(...) {
//insert values to emp object for n number of times;
}
empList.add(emp); //add emp.object to empList;
return empList;
}
Now while inserting these values to UI; Need to compare objects in the list; where any two or more objects matches with each other or not?
Based on the assumption that you want to eliminate the duplicates from the list and do not show duplicates on GUI.
Use Set collection, it automatically takes care of duplicates.
A collection that contains no duplicate elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at
most one null element. As implied by its name, this interface models
the mathematical set abstraction.
Override equals() and hashcode() methods.
References:
On equals and hashcode in Java
Overriding equals and hashcode
You could override equals method for that class to compare the objects of the same class the way you want.
Default equals method:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Link about overriding equals:
http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html
One simple method of doing this is to just do a double for loop.
public static List<Employee> getList(List<Employee> oldList)
{
List<Employee> empList = new ArrayList<Employee>();
for (int i = 0; i < oldList.size; i++)
{
for (int j = 0; j < oldList.size; j++)
{
//compare oldList.get(i) with oldList.get(j)
//if match, set some boolean
}
//if duplicate found, delete one copy, or add one to new list, etc
}
This allows you to go through each element in the outer loop, and compare to every other element in the inner loop.
I guess employee id (empid) is unique for each emplyee, yes?
If so, use a hash instead where empid is the key and employee object is the value.
Map<Long, Employee> empmap = new HashMap<Long, Employee>();
empmap.put(currentEmployee.getEmpid(), currentEmployee)

How to sort three arrays in java?

I have three arrays in my proggramme Surname, Forename and result and need to create a sort array
Surname: Chris Forename: Charleton: Result: 54
Surname: Annett: forename: Lyle: result 67
If I wanted to sort it by alphabetical of last name, i need all the fields to move, instead of just the surname. This is the bubble sort code i'm working off
int swap;
boolean swapflag = true;
//outer loop
while (swapflag == true)
{
swapflag = false;
//inner loop
for (int index=0; index < (nums.length - 1); index++)
{
//swap routine
if (nums[index]> nums[index + 1])
{ //swap routine
swap = nums[index];
nums[index] = nums[index + 1];
nums[index + 1] = swap;
swapflag = true;
}
}//end inner
}//end outer
System.out.println ("\nArray Contents after sorting"
+ "\n*************");
for (int index=0; index < nums.length; index ++)
{
System.out.println("Array element "
+ index + ": " + nums[index]);
}
}
}
` package projStudent;
import java.util.Scanner;
public class UnitResults
{
//delcare Scanner as keyb
static Scanner keyb = new Scanner (System.in);
//declare fields
static String studentForename [];
static String studentSurname [];
static int [] studentResult;
static int pointer;
//constructor
UnitResults(int sizeofclass)
{//start of constructor
studentForename = new String [sizeofclass];
studentSurname = new String [sizeofclass];
studentResult = new int [sizeofclass];
pointer = 0;
}//end of constructor
public boolean add(String studentForename[], String studentSurname[],
int studentResult[])
{//start of add method
if (pointer == studentResult.length )
{//start of if statement
System.out.println("Sorry Array is full");
return false;
studentResult[pointer] = studentResult[];
pointer ++;
}//end of if statement
}//end of add method
public boolean delete(int element)
{//start of delete method
element = element - 1;
if ((element >= 0) && ( element < pointer))
{//start of if statement
for(int index = (element + 1); index < pointer; index++)
{//start of for statement
studentResult[index - 1] = studentResult[index];
}//end of for statement
pointer--;
return true;
}//end of if statement
else
{//start of else statement
return false;
}//end of else statement
}//end of delete method
public String find()
{//start of display
String strOutput="";
strOutput = strOutput + "Students";
if (pointer==0)
{//start of if statement
strOutput = strOutput + "There are no records in this Array";
return strOutput;
}//end of if statement
for (int index=0; index < pointer; index++)
{//start of for method
strOutput = strOutput + "Student Name" + studentSurname[index] + studentForename +
"Student Result" + studentResult +"\n";
}//end of for method
return strOutput;
}//display
public int sort (int UnitResults)
{//start of sort
int sort;
boolean swapflag = true;
while (swapflag == true)
{//start of while loop
swapflag = false;
for (int index=0; index < (UnitResults - 1); index++)
{
if (studentResult[index]> studentResult[index + 1])
{ //swap routine
sort = studentResult[index];
studentResult[index] = studentResult[index + 1];
studentResult[index + 1] = sort;
swapflag = true;
}
}
}//end of while loop
}//end of sort
}`
Unfortunately, your post is confusing as you don't include some things, like just what is the current array you are sorting. Still, if I understand your question correctly...
Regardless of the language, your strategy would involve changes to how you swap the elements. If your array consists of composite data, then simply assigning in a swap is fine. If your data is scattered, then your swap needs to swap each variable. You can always just sort the indices of the array into another array, then use that array to indirectly reference the first, for sorted access.
I would suggest you use an List for this purpose.
First create an object. For example "Person" containing members for "Forname","Surename","Result". Then fill the list with these objects, implement the Interface Compareable and use the Collection.sort() methode.
class Person implements Comparable<Person>
{
private String forname;
private String surname;
private int rating;
public Person(String forename, String surname, int rating)
{
this.forname = forename;
this.surname = surname;
this.rating = rating
}
public int compareTo(Person p) {
if(p.rating == this.rating)
return 0;
else if(p.rating < this.rating)
return -1;
return 1;
}
}
class Test{
public static void main(String[] args){
List<Person> personList = new ArrayList<Person>();
Person p1 = new Person("John","Smith",10);
Person p2 = new Person("Max","Muster",20);
Person p3 = new Person("Sarah","Clark",15);
personList.add(p1);
personList.add(p2);
personList.add(p3);
personList.sort();
}
}
There are a number of features of the Java programming languages that can help you resolve the problem that you are having, the first of which is inclusion of appropriate data structures and methods with which to manipulate objects within those data structures.
First and foremost, I'd recommend using a java class to represent a single person entity... think about it, when you look up a person's information, you don't consult three separate books, or computer screens, or what have you, when all that information can be organized into one place. For your person above, for example, you could use something like this:
public class Person implements Comparable<Person> {
public String firstName;
public String lastName;
public int result;
public Person(String fn, String ln, int r) {
firstName = fn;
lastName = ln;
result = r;
}
public int compareTo(Person otherPerson) {
return lastName.compareTo(otherPerson.lastName);
}
}
This will give you an object that will store all of your person information, and by default will be easily sortable by last name (you can change this behavior with a comparator, which I won't cover here.)
Now instead of having three different arrays of first names, last names, and results, you can have a single array of Persons. There ARE actually sorting mechanisms within the java language for arrays already, which you can research and use if you choose, but if you'd like to use your own sort, you would just need to replace your swap conditional with something like this:
if(persons[index].compareTo(persons[index+1]) > 0) {
...
}
i just want ask you
why instead creating class student ie
class Student{
private String studentForename;
private String studentSurname;
private int studentResult;
//setters and getters
}
and put them in some collection ie List
you are putting them into 3 different arrays?
do you realize, if you have them nicely in the list, you can sort them just by using Collections.sort() ?
Can't understand properly the question: are you looking for a way to manually implement a sorting algorithm (bubble, quick or whatever) or you would like to simply sort them the best you can? Generally speaking you should never implement your own sort 'cause Java provides itself a very efficient lot... or is this an exercise? Probably :)
Best way I can imagine is, provided the 3 arrays in their original form are linked by index, create a surname/index map, load it form surname array, sort the Map.Entry by key and then you will have the array indexes sorted the way you wanted. Check here for more details: how to sort Map values by key in Java
PS The solutions provided by the others are correct and preferrable if you are NOT doing an exercise :) Better deal with a structured object than with 3 separated data.

Categories