delete object out of arraylist Java - java

Here i have create a delete method that will search through the Object array and remove the selected object.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
private String name;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[20];
}
DogList(String name) {
this.name = name;
}
public void deleteItem(DogList gi) {
int i = 0;
while( (i < numItems) && (gi != dogListArray[i]) ) {
i++;
}
if(i == numItems) {
// Throw exception if there is not matching Item
throw new NoSuchElementException("That item does not exists");
}
int pos = i;
while(pos < numItems -1 ) {
dogListArray[pos] = dogListArray[pos + 1];
pos++;
}
numItems --;
}
I cant wrap my head around why in the first while loop the (gi != dogListArray[i]) is throwing an error:"Incompatible operand types DogList and DogItem"
Any help would be wonderful.
The code is pretty long so if you want to see any part i will edit and show what is needed.

I am assuming that dogListArray is a DogItem[], making dogListArray[i] a DogItem. I assume that gi is meant to be a DogItem as well rather than a DogList?
On a separate but still relevant note, you should use the equals method, rather than == or !=, to compare objects. See here an explanation of this aspect.

Related

How to use compareTo while iterating through an array

What is the correct way to use the compareTo inside for loop? I'd like to sort the Course objects in ascending order inside the array. I'm worried about the correct syntax for compareTo inside a loop in my insert() method.
if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0) - is giving me error.
public class Courses implements Comparable{
private String title;
private int courseNumber;
private Courses[] array;
private int size;
public Courses(String title, int courseNumber){
this.title = title;
this.courseNumber = courseNumber;
this.array = new Courses[10];
this.size = 0;
}
public void insert(String title, int courseNumber){
Courses object = new Courses(title, courseNumber);
if(size == 0){
array[0] = object;
}
else{
int i;
for(i = 0; i < size; i++){
if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)
//do STUFF
}
}
}
#Override
public int compareTo(Object o) {
if(o instanceof Courses){
Courses obj1 = (Courses)o;
return this.courseNumber - obj1.courseNumber;
}
return -1;
}
}
if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)
Is giving you an error because courseNumber is a primitive (not an object), so there is no compareTo method defined on it.
If you would like to use that syntax to compare integers, you can use the static Integer.compare method.
if(Integer.compare(array[i].courseNumber, object.courseNumber) <= 0)
If you want to use your defined compareTo method then do
if(array[i].compareTo(object) <= 0))
Hint : You are not passing the object as parameter.
How does this compare two objects ?
for(i = 0; i < size; i++){
if((array[i].courseNumber.compareTo(object.courseNumber)) <= 0)
//do STUFF
}
You should look at Arrays.sort(Object[]) which will take care about ordering it using the Comparable interface.

Palindrome with Array based stack and queue check

For an assignment we are applying what is said in the title. i have written all the code out, but when I am compiling the code i get four errors dealing with the line 19 of code.
while(!myQueue<String>.isEmpty() & !myStack.isEmpty()){
this is the full code if it also helps
import java.util.*;
public class Palindrome{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String userInputConversion;
String userInput;
MyStack myStack = new MyStack();
MyQueue<String> myQueue = new MyQueue<String>();
System.out.println("Enter in a possible Palindrome. ");
userInputConversion = scan.next();
userInput = userInputConversion.toLowerCase();
String s = new String();
for(int i = 0; i < userInput.length(); i++){
s = "" + userInput.charAt(i);
System.out.print(s);
myQueue.enqueue(s);
myStack.push(s);
}
while(!myQueue<String>.isEmpty() & !myStack.isEmpty()){
String deQueued = myQueue.dequeue();
String popped = myStack.pop();
if(deQueued == popped)
System.out.println("Input is a palindrome. ");
else
System.out.println("input isnt a palindrome. ");
}
}
}
class MyStack{
private String[] stack;
private int top;
public MyStack(){
stack = new String [100];
top = 0;
}
public String push(String pushP){
if(top >= stack.length){
System.out.println("Error: MyStack.push(): stack overflow");
return "yes";
}
stack[top] = pushP;
top++;
}
public String pop(){
if(top <= 0){
System.out.print("Error in MyStack.pop(): stack empty");
return "n";
}
top--;
return stack[top];
}
public boolean isEmpty(){
if(top == 0){
return true;
}
else{
return false;
}
}
`}
class MyQueue<String> implements Iterable<String> {
private String[] queue;
private int front = 0;
private int rear = 0;
private int currentSize = 0;
public MyQueue(){
queue = (String[])(new Object[1]);
front = 0;
rear = 0;
currentSize = 0;
}
public boolean isEmpty() {
return (currentSize == 0);
}
public int currentSize() {
return currentSize;
}
public void enqueue(String String) {
if (currentSize == queue.length - 1) {
resize(2 * queue.length);
}
queue[rear++] = String;
if (rear == queue.length) {
rear = 0;
}
currentSize++;
}
public String dequeue() {
if (this.isEmpty()) {
throw new RuntimeException("Tried to dequeue an empty queue");
}
else {
String itemToReturn = queue[front];
queue[front++] = null;
currentSize--;
if (front == queue.length) {
front = 0;
}
if (currentSize == queue.length / 4) {
resize(queue.length / 2);
}
return itemToReturn;
}
}
private void resize(int capacity) {
String[] newArray = (String[]) new Object[capacity];
for (int i = 0; i < currentSize; i++) {
newArray[i] = queue[(front + i) % queue.length];
}
queue = newArray;
front = 0;
rear = currentSize;
}
}
if anyone can help that would be great or give some pointers.
For your 2nd compilation error, The type MyQueue<String> must implement the inherited abstract method Iterable<String>.iterator(), you can either
implement the public Iterator<String> iterator() method
remove the implements Iterable<String> statement
or make MyQueue abstract
Making MyQueue abstract won't help you much & I also don't see any place in the code where you need an iterator or make use of the fact that MyQueue is Iterable. Being a queue, you would want to use its signature methods - enqueue & dequeue. So, you can safely go for option 2. Else to implement, this answer should help.
You also haven't implemented the concept of type arguments perfectly. You would want to use a Type Parameter in the class definition; e.g. class MyQueue<String> becomes class MyQueue<T>. Likewise the member variables & methods would also change.
You 3rd compilation error, This method must return a result of type String is simply because your push() method doesn't have a return statement at the end. It's better to simply make it void, since you're not using the returned String "yes" anywhere. For StackOverflow, you can throw an RuntimeException, just like you did in your dequeue.
Few pointers
You've made the classic mistake of comparing Strings with == instead of .equals() in the statement if (deQueued == popped).
Make it a practice to close your scanner/resources, even though in this case there's no harm.
You have a little logical error in your while loop that compares the characters - I'll let you figure that one out.
First of all your making things Complex, for a simple string why do you want use stack or queue . i guess below logic would help you
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");

Sorting an ArrayList so that certain numbers go first, and the order is otherwise preserved

public static ArrayList<ArrayList<HSSFCell>> newTogether(ArrayList<ArrayList<HSSFCell>> sheetData) {
ArrayList<ArrayList<HSSFCell>> temporary = new ArrayList<ArrayList<HSSFCell>>();
for(int i = 0; i < sheetData.size(); i++) {
ArrayList<HSSFCell> list = sheetData.get(i);
if (list.get(3).getCellType() == Cell.CELL_TYPE_NUMERIC) {
if(Integer.parseInt(list.get(3).getStringCellValue()) > 100) {
temporary.add(list);
sheetData.remove(i);
i--;
}
}
}
for(int i = 0; i < sheetData.size(); i++) {
ArrayList<HSSFCell> list = sheetData.get(i);
temporary.add(list);
}
return temporary;
}
What I am trying to do with my code is have the 2D ArrayList take out any numbers greater than 100 and put them in the beginning of the ArrayList, while preserving the order of the remaining elements. However, this code just returns an ArrayList in the original order, and if I add a println to either if, I get nothing. Could someone point out what it is I'm doing wrong?
Have you tried putting a println in front of the first if to check what getStringCellValue() returns?
btw. since Collections.sort is guaranteed to be stable according to the API documentation, you could use that. Should be faster than your way of doing it.
That could look like this
private static boolean biggerThan100(ArrayList<HSSFCell> list) {
return list.get(3).getCellType() == Cell.CELL_TYPE_NUMERIC &&
(Integer.parseInt(list.get(3).getStringCellValue()) > 100);
}
public static ArrayList<ArrayList<HSSFCell>> newTogether(ArrayList<ArrayList<HSSFCell>> sheetData) {
ArrayList<ArrayList<HSSFCell>> temp = new ArrayList<>(sheetData);
Collections.sort(temp, new Comparator<ArrayList<HSSFCell>>() {
public int compare(ArrayList<HSSFCell> a, ArrayList<HSSFCell> b) {
if(biggerThan100(a) && !biggerThan100(b)) return -1;
else if(biggerThan100(b) && !biggerThan100(a)) return 1;
else return 0;
}
});
return temp;
}

Using Comparable's compareTo to compare an object to the elements in an arraylist

I created an object Student using Comparable with getters/setters as well as a method that overrides compareTo. In a separate file an arraylist of objects is populated from a text file. Now I need to compare the values in the arraylist to another Student object.
The file was used to create an arraylist as below:
try {
private static ArrayList<Student> array = new ArrayList<Student>();
File file = new File("students.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String inline = scanner.nextLine();
String[] split = inline.split(":");
Student myStudent = new Student();
myStudent.setUsername(split[0]);
myStudent.setPassword(split[1]);
array.add(myStudent);
}
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("ERROR.");
}
The text file looks like this:
John:password1
Jane:password2
Jack:password3
(One on each line, no blank lines in between.)
And in a separate method a created Student object is compared to the elements in the arraylist:
Student aStudent = new Student();
aStudent.setUsername("student");
aStudent.setPassword("password");
boolean found = false;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break;
}
else
{
System.out.println("No such records found!");
found = false;
break;
}
System.out.println(found);
}
The problem is that the object aStudent is not being compared with the objects in the arraylist. It does not print out anything (a -1, 0, or 1) for the call to compareTo, but it always shows that found is true, even though it should be false when there are no matches for aStudent in the file (which there aren't any matches to the username "student" or the password "password").
All together my code complies and works - it just works incorrectly.
Sorry if this sounds confusing. In short, my question is how can I compare the objects of an arraylist to another object using the Comparable interface and compareTo? A plus is if you can tell me what I'm doing wrong.
Thank you in advance.
EDIT
Here is the overriding of the compareTo method:
public int compareTo(Student obj){
int result = 1;
if ((this.Username.compareToIgnoreCase(object.Username) < 0) || (this.Password.compareTo(object.Password) < 0))
{
result = -1;
}
else if ((this.Username.compareToIgnoreCase(object.Username) == 0) && (this.Password.compareTo(object.Password) == 0))
{
result = 0;
}
return result;
}
More context would be useful, but your for-loop looks wrong...
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break; // out of loop
}
else
{
System.out.println("No such records found!");
found = false;
break; // break out loop
}
System.out.println(found);
}
The break statement is used to break out of the loop, meaning that you will only ever compare the first element in the list.
The entire else branch isn't required (or at least I don't think it is ;)), for example...
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break; // out of loop
}
}
System.out.println(found);
Updated
Based on you new compareTo code snippet, this...
if ((this.Username.compareToIgnoreCase(object.Username) < 0) || (this.Password.compareTo(object.Password) < 0))
{
result = -1;
}
else if ((this.Username.compareToIgnoreCase(object.Username) < 0) && (this.Password.compareTo(object.Password) < 0))
{
result = 0;
}
seems wrong to me...the else if should be more like
else if ((this.Username.compareToIgnoreCase(object.Username) == 0) && (this.Password.compareTo(object.Password) == 0))
if the contract for the Comparable interface is to be met, where 0 is equal...
For example...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private static ArrayList<Student> array = new ArrayList<Student>();
public static void main(String[] args) {
array.add(new Student("John", "password1"));
array.add(new Student("Jane", "password2"));
array.add(new Student("Jack", "password3"));
Student aStudent = new Student("Jack", "password3");
boolean found = false;
for (int i = 0; i < array.size(); i++) {
if (array.get(i).compareTo(aStudent) == 0) {
System.out.println(aStudent.equals(array.get(i)));
found = true;
break;
}
}
System.out.println(found);
}
public static class Student implements Comparable<Student> {
private String name;
private String password;
public Student(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int compareTo(Student object) {
int result = 1;
if ((this.getName().compareToIgnoreCase(object.getName()) < 0) || (this.getPassword().compareTo(object.getPassword()) < 0)) {
result = -1;
} else if ((this.getName().compareToIgnoreCase(object.getName()) == 0) && (this.getPassword().compareTo(object.getPassword()) == 0)) {
result = 0;
}
return result;
}
}
}
Which will print out...
false
true
Where the objects are not equal but where they are comparable...which is kind of weird...to me ;)
Your problem may lie in the compareTo function that you overrode, you need to include that code otherwise no one can determine why certain values are being returned
EDIT:
Note that when objects are created, they are not necessarily equal solely because their contained values are equal. They are separate instances of the object and treated as such.
You will need to override the equals function as well, not just the compareTo function, in order to get the result that you seek.

Null pointer Exception in CompareTo method

Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)

Categories

Resources