I have an array and I am implementing a priority queue with it. Now, I cam not shift the elements(since only the front pointer has to move).
I tried that by adding null to that array position but it just does not work since I have used Arrays.sort(arr) methods and if I do make the position null, it gives NullPointerException.
Here is how my code looks:
public static void remove() {
//Priorityy x = arr[front];
arr[front] = null;
front--;
//return x;
}
public int compareTo(Priorityy pe) {
if (this == null || pe == null)
return 0;
else {
if (this.key < pe.key) {
return 1;
} else if (this.key > pe.key) {
return -1;
} else {
return 0;
}
}
}
Where did I go wrong?
Use Arrays.copyOfRange to get an array without the first element (front) as follows:
arr = Arrays.copyOfRange(1, arr.length);
Related
I'm creating a resizeable Object Array. Below is my add function in which I pass through the object I want to add into my arraylist.
The function works, however if someone could explain this code
temp[theList.length] = toAdd;
I understand that it's adding the parameter argument to the end of the new Arraylist. But what's confusing me is the index that I pass into temp[]. Shouldn't I be including theList.length + 1 rather than just theList.length?
public boolean add(Object toAdd) {
if (toAdd != null) {
Object[] temp = new Object[theList.length + 1];
for (int i = 0; i < theList.length; i++) {
temp[i] = theList[i];
}
temp[theList.length] = toAdd;
theList = temp;
return true;
} else {
System.out.println("Invalid type");
return false;
}
}
Explanation for the add method:
Assume, the size of the theList is 10.
They have created an temp array which takes size as theList + 1, so size of temp is 11.
Now, objects are added to the temp except for the last element tem[10].
For adding the last element, you can use any of the 2 ways:
temp[theList.length] //temp[10]
Or
temp[temp.length-1] //temp[10]
They used the 1st way to add the toAdd object.
You could use a standard method Arrays.copyOf which immediately creates a copy of the input array with the new size (in this case, the length is increased):
import java.util.Arrays;
//...
public boolean add(Object toAdd) {
if (toAdd != null) {
int oldLength = theList.length;
theList = Arrays.copyOf(theList, oldLength + 1);
theList[oldLength] = toAdd;
return true;
} else {
System.out.println("Cannot add null object");
return false;
}
}
I'm very new to recursion (and I'm required to use it) and am having some serious logic trouble using one of my search methods. Please see below:
//these are methods within a Linked List ADT with StringBuilder functionality
//the goal here is to access the char (the Node data) at a certain index
public char charAt(int index)
{
if((firstNode == null) || (index < 0) || (index >= length + 1))
//firstNode is the 1st Node in the Linked List, where the search begins
{
System.out.println("Invalid Index or FirstNode is null");
IndexOutOfBoundsException e = new IndexOutOfBoundsException();
throw e;
}
else
{
char c = searchForChar(firstNode, index);
return c;
}
}
private char searchForChar(Node nodeOne, int index)
{
int i = 0;
if(nodeOne == null) //basecase --> end
{
i = 0;
System.out.println("nodeOne null, returning null Node data");
return 'n';
}
else if(i == index) //basecase --> found
{
i = 0;
return nodeOne.data; //nodeOne.data holds the char in the Node
}
else if(nodeOne != null) //search continues
{
searchForChar(nodeOne.next, index);
i++;
return nodeOne.data;
}
return nodeOne.data;
}
The output is length-1 prints of "nodeOne null, returning null Node data". I don't understand how the recursive statement in the last else-if statement if being reached when it seems like the null statement in the first if statement is being reached as well.
I tried rearranging the if statements so that the if(nodeOne != null) is first, but that gives me a NullPointerException. Not sure what I'm doing wrong. Especially because I can print the data in the Nodes using a toString() method so I know the Nodes don't have null data.
Can anyone please help me understand?
I wrote a complete example I hope this is what you need. If you would loop over the string StackOverflow with i < 14 it will also print the null character \0 if you would use i < 15 it will give you a IndexOutOfBoundsException. By reducing index by 1 every time you are actually saying I need to (index - 1) hops to my destination node.
public class CharTest {
public static class Node {
private char content;
private Node nextNode;
public Node () {
content = '\0';
nextNode = null;
}
public Node (String str) {
Node temp = this;
for (int i = 0; i < str.length(); i++) {
temp.content = str.charAt(i);
temp.nextNode = new Node();
temp = temp.nextNode;
}
}
public char charAt(int index) {
if (index == 0) {
return content;
} else if (index < 0 || nextNode == null) {
throw new IndexOutOfBoundsException();
}
return nextNode.charAt(index - 1);
}
}
public static void main(String[] args) {
Node test = new Node("StackOverflow");
for (int i = 0; i < 13; i++) {
System.out.print(test.charAt(i));
}
System.out.println();
}
}
I will leave making a toString() method either iteratively or recursively an exercise to the reader. But using a StringBuilder or a char[] would be a good idea, because of a performance reasons.
While iterating the two lists and displaying the items in the layouts i m getting the Array Index out of bounds exception at the line below.How can we have a null check or a condition with which i wont get the error
ParallelList<BaseItem> list = new ParallelList<BaseItem>(highlighted, normal);
for (List<BaseItem> ints : list) {
final BaseItem itemH = ints.get(0);
if(!ints.get(1).equals(null) && ints.size()!=0){ // error here at this line
final BaseItem itemn = ints.get(1);
}
using the below parallellist for this
public class ParallelList<T> implements Iterable<List<T>> {
private final List<List<T>> lists;
public ParallelList(List<T>... lists) {
this.lists = new ArrayList<List<T>>(lists.length);
this.lists.addAll(Arrays.asList(lists));
}
public Iterator<List<T>> iterator() {
return new Iterator<List<T>>() {
private int loc = 0;
public boolean hasNext() {
boolean hasNext = false;
for (List<T> list : lists) {
hasNext |= (loc < list.size());
}
return hasNext;
}
public List<T> next() {
List<T> vals = new ArrayList<T>(lists.size());
for (int i=0; i<lists.size(); i++) {
if(loc < lists.get(i).size()){
vals.add(lists.get(i).get(loc));
}
// vals.add(loc < lists.get(i).size() ? lists.get(i).get(loc): null);
}
loc++;
return vals;
}
public void remove() {
for (List<T> list : lists) {
if (loc < list.size()) {
list.remove(loc);
}
}
}
};
}
}
Error is here
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
You should reverse the conditions. First make sure the size of the list is large enough (i.e. it has more than one element), and only then attempt to access the second element of the list :
if(ints.size() > 1 && ints.get(1) != null)
Turn it around:
if(ints.size()!=0 && !ints.get(1).equals(null))
The && connection is evaluatef from left to right. So when the size is 0 then the left part is false already. The full && expression cannot be true regarless what !ints.get(1).equals(null) gets evaluated to. Therefore it will not be executed at all.
BTW, the first element has the index 0. You really want to use:
if(ints.size()!=0 && !ints.get(0).equals(null))
or
if(ints.size()<=2 && !ints.get(1).equals(null))
PS: Having a closer look at the error message, it turns out that the latter really fixes your problem. Size is actually 1 but you are accessing the second item with the index 1. (Again, first index is 0)
You should try these conditions
if(!ints.isEmpty()){
final BaseItem itemH = ints.get(0);
if( ints.size()>=1 && !ints.get(1).equals(null) ){
final BaseItem itemn = ints.get(1);
}
}
}
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)
Using binarySearch never returns the right index
int j = Arrays.binarySearch(keys,key);
where keys is type String[] and key is type String
I read something about needing to sort the Array, but how do I even do that if that is the case?
Given all this I really just need to know:
How do you search for a String in an array of Strings (less than 1000) then?
From Wikipedia:
"In computer science, a binary search is an algorithm for locating the position of an element in a sorted list by checking the middle, eliminating half of the list from consideration, and then performing the search on the remaining half.[1][2] If the middle element is equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for search based on whether the element is greater than or less than the middle element."
So the prerequisite for binary search is that the data is sorted. It has to be sorted because it cuts the array in half and looks at the middle element. If the middle element is what it is looking for it is done. If the middle element is larger it takes the lower half of the array. If the middle element is smaller it the upper half of the array. Then the process is repeated (look in the middle etc...) until the element is found (or not).
If the data isn't sorted the algorithm cannot work.
So you would do something like:
final String[] data;
final int index;
data = new String[] { /* init the elements here or however you want to do it */ };
Collections.sort(data);
index = Arrays.binarySearch(data, value);
or, if you do not want to sort it do a linear search:
int index = -1; // not found
for(int i = 0; i < data.length; i++)
{
if(data[i].equals(value))
{
index = i;
break; // stop looking
}
}
And for completeness here are some variations with the full method:
// strict one - disallow nulls for everything
public <T> static int linearSearch(final T[] data, final T value)
{
int index;
if(data == null)
{
throw new IllegalArgumentException("data cannot be null");
}
if(value == null)
{
throw new IllegalArgumentException("value cannot be null");
}
index = -1;
for(int i = 0; i < data.length; i++)
{
if(data[i] == null)
{
throw new IllegalArgumentException("data[" + i + "] cannot be null");
}
if(data[i].equals(value))
{
index = i;
break; // stop looking
}
}
return (index);
}
// allow null for everything
public static <T> int linearSearch(final T[] data, final T value)
{
int index;
index = -1;
if(data != null)
{
for(int i = 0; i < data.length; i++)
{
if(value == null)
{
if(data[i] == null)
{
index = i;
break;
}
}
else
{
if(value.equals(data[i]))
{
index = i;
break; // stop looking
}
}
}
}
return (index);
}
You can fill in the other variations, like not allowing a null data array, or not allowing null in the value, or not allowing null in the array. :-)
Based on the comments this is also the same as the permissive one, and since you are not writing most of the code it would be better than the version above. If you want it to be paranoid and not allow null for anything you are stuck with the paranoid version above (and this version is basically as fast as the other version since the overhead of the method call (asList) probably goes away at runtime).
public static <T> int linearSearch(final T[] data, final T value)
{
final int index;
if(data == null)
{
index = -1;
}
else
{
final List<T> list;
list = Arrays.asList(data);
index = list.indexOf(value);
}
return (index);
}
java.util.Arrays.sort(myArray);
That's how binarySearch is designed to work - it assumes sorting so that it can find faster.
If you just want to find something in a list in O(n) time, don't use BinarySearch, use indexOf. All other implementations of this algorithm posted on this page are wrong because they fail when the array contains nulls, or when the item is not present.
public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
To respond correctly to you question as you have put it. Use brute force
I hope it will help
public int find(String first[], int start, int end, String searchString){
int mid = start + (end-start)/2;
// start = 0;
if(first[mid].compareTo(searchString)==0){
return mid;
}
if(first[mid].compareTo(searchString)> 0){
return find(first, start, mid-1, searchString);
}else if(first[mid].compareTo(searchString)< 0){
return find(first, mid+1, end, searchString);
}
return -1;
}
Of all the overloaded versions of binarySearch in Java, there is no such a version which takes an argument of String. However, there are three types of binarySearch that might be helpful to your situation:
static int binarySearch(char[] a, char key);
static int binarySearch(Object[] a, Object key);
static int binarySearch(T[] a, T key, Comparator c)