Generic array index out of bounds - java

Ok , here is my problem . I'm learing to use generic classes and methods. I want to make an generic array list and method that will add/remove element by choosen index. I simply doesn't know how to do that . My example is calling an IndexOutOfBoundsException.
Any help is welcome.
Thanks it advance .
class klasa3:
public class klasa3<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
public klasa3(int initSize){
}
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o,int indeks) {
o = list.get(indeks);
list.add(o);
}
public E pop(int indeks) {
E o = list.get(indeks);
list.remove(indeks);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public String toString() {
return "stack: " + list.toString();
}
}
main class:
public class klasa2 {
public static void main(String[] args ) {
klasa3 stak2 = new klasa3(13);
stak2.push("cola",2); // problem here
stak2.pop(2);
System.out.println(stak2.getSize());
}
}

You're creating an empty ArrayList, and then trying to get the third element (element at index 2) from it within your push method. That's not going to work.
Now, you're currently ignoring your initSize parameter in your constructor. You might want something like:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize) {
for (int i = 0; i < initSize; i++) {
list.add(null);
}
}
Or provide a default element:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize, E element) {
for (int i = 0; i < initSize; i++) {
list.add(element);
}
}

This is what is happening:
In the main method you first create a new klasa3 object. Then you call push("cola", 2) on it.
The push method does: o = list.get(indeks), where indeks is 2. At this point the list is empty, so 2 is not a valid index, which causes an IndexOutOfBoundsException.
The index that you pass to the get method must be between 0 (inclusive) and the size of the list (exclusive). Since the size is 0, the index 2 is invalid.

Related

Need the Index No of an Array List, by giving the certain text of the element String

I want to get the particular index of the array list, by using only contained text. Say suppose,
I have arraylist as
Test = {"LabTechnician","SeniorLabTechnician_4","Pathologist","SeniorLabTechnician_6"}
If want the index nos of both the SeniorLabTechnician, i have to use the exact string in the indexOf and lastindexOf method. Like Test.indexOf("SeniorLabTechnician_4") and Test.lastindexOf("SeniorLabTechnician_6")
this is will get me the exact answer.. But instead of that,by using only prefix say like senior or some thing like, i want the exact same answer before..
Like
Test.indexOf("Senior") and Test.lastindexOf("Senior")...
Please suggest
Loop over the list and compare the elements with contains:
int indexOfContains(List<String> lst, String what) {
for(int i=0;i<lst.size();i++){
//this will make the check case insensitive, see JAVY's comment below:
//if(lst[i].toLowerCase().contains(what.toLowerCase())) {
if(lst[i].contains(what)){
return i;
}
}
return -1;
}
If you want something like lastIndexOf then just reverse the order in which the list is iterated.
As I understand, you want to modify default behaviour of indexOf and lastIndexOf methods of ArrayList.
My solution is create a new class CustomArrayList extends ArrayList.
Override indexOf method
Override lastIndexOf method
public class CustomArrayList extends ArrayList {
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size(); i++)
if (get(i) == null)
return i;
} else {
for (int i = 0; i < size(); i++)
if(o instanceof String) {
if(get(i).toString().startsWith(o.toString())) {
return i;
}
} else {
if (o.equals(get(i)))
return i;
}
}
return -1;
}
public static void main(String[] args) {
List list = new CustomArrayList();
list.add("LabTechnician");
list.add("SeniorLabTechnician_4");
list.add("Pathologist");
list.add("SeniorLabTechnician_6");
System.out.println(list.indexOf("Senior"));
}
}
I left overriding of lastindexof method for you.
private int getsearchPos(String searchvalue) {
for(String hj : Test)
{
if(hj.toLowerCase().startsWith(searchvalue.toLowerCase()))
return Test.indexOf(hj);
}
return -1;
}
this should help.

Assignment involved with creating methods

first of all thank you for looking at my question. My assignment is pretty basic to most but I am an inexperienced programmer. Here is the description of the assignment:
Your objective is to write a class called Storage that can hold a collection of Strings. It must implement the following methods:
addItem(String s) - This method accepts a String parameter and returns a boolean value. The parameter reference is then stored internally in your choice of structure. The method returns true if the reference is successfully added.
getItems() - This method takes no parameters and returns an array containing all the Strings stored in the internal structure. The returned array must not contain any null elements.
isFull() - This method returns true if there is no internal storage available, otherwise false.
removeItem(String s) - This method accepts a String parameter and returns a boolean value. The method must search through the internal storage structure and remove the parameter reference (if present). The method returns true if the reference is successfully removed, otherwise false.
I am completely stumped on most of these. I am using an array to store the data, but I am open to other suggestions. Thanks again.
Alright guys I made a few changes and I started some code, but it won't compile correctly. Based on the description of the methods can someone tell me what I'm doing wrong?
public class Storage {
//variables
private String[] list;
private int size = 10;
private int index = 0;
public boolean addItem(String s) {
for (int i = 0; i < list.length; i++) {
if (!list.equals(null)) {
list[i] = s;
}
}
return true;
}
public String[] getItems() {
for (int i = 0; i < list.length; i++) {
if(!list.equals(null)) {
System.out.println(list[i]);
i++;
}
}
return list;
}
public boolean isFull() {
if (list.length > size) {
System.out.println("The array is full");
}
return true;
}
public boolean removeItem(String s) {
for (int i = index; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
return true;
}
}
addItem(String s): The method should return a boolean value, since you are using an ArrayList, we can use add(Object o), which returns a boolean.
public boolean addItem(String s) {
return list.add(s); // I'm assuming that your instance variable is named list
}
getItems(): Use the method in the ArrayList class called toArray(), passing in an argument of the array type to cast to.
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
isFull(): Not exactly sure what your instructor was asking for here, as an ArrayList will automatically resize, but you could just add an instance variable to your class that contains a maximum size and then check against it like so...
public static final int SIZE = 10;
...
public boolean isFull() {
return list.size() >= SIZE;
}
of course, this means adding code to check that the element you're adding doesn't breach capacity. I'll show this in the complete example below.
removeItem(String s): The remove() method in ArrayList is overloaded to accept an object to remove. Likewise, this method also returns a boolean value.
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
All in all, you should have something similar to the following...
public class Storage {
private ArrayList<String> list = new ArrayList<>();
public static final int SIZE = 10;
public boolean addItem(String s) {
if (isFull())
return false;
return list.add(s);
}
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
public boolean isFull() {
return list.size() >= SIZE;
}
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
}

How to add an Object to a Generic array using a method Java

I want to add an object to my array. I am trying to create a method so whenever it's called, it adds the generic type object. Here's my code:
public class ArrayObjects<E> implements SomeImp<E>{
private E[] list;
private int maxCapacity, currentSize;
public ArrayObjects(){
maxCapacity = 10;
array = (E[]) new Object[maxCapacity];
}
public void addObj(E obj){
array.add(obj); //Throws an error
}
}
Eclipse shows me an error though. It says "Cannot invoke add(E) on the array type E[ ]"
Does anyone know why does this happen? Do you know of an alternative of adding an object to my generic array?
Thank you!
EDIT:
When I create an instance of a class that instantiates ArrayObjects, and try to add a value to it, it doesn't do it. code:
import packageWhereArrayObjectsIs.*;
public class Test {
private ArrayObjects<Integer> list;
public Test() {
list = new ArrayObjects<Integer>();
Test();
}
private void TestOne() {
for(int i=1; i <= 10; i++)
list.addLast(i);
System.out.println("Should print 1 .. 10");
System.out.println(list);
}
}
The method add() does not exist for arrays. You must access array elements using the correct syntax []:
public void addLast(E obj) {
array[currentSize++] = obj;
}
In order for your list to print nicely, you'll want to add a toString() method to your ArrayObjects class:
public String toString() {
return Arrays.toString(array);
}
To iterate over the elements of your ArrayObjects, you can implement the Iterable interface:
public class ArrayObjects<E> implements Iterable<E>
This requires your class to have an iterator() method that returns an Iterator:
public Iterator<E> iterator() {
class It implements Iterator<E>
{
int position = -1;
public boolean hasNext() {
return position + 1 < currentSize;
}
public E next() {
return array[++position];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
return new It();
}
Finally, this code shows how you can now iterate over your list using an enhanced for loop:
ArrayObjects<Integer> list = new ArrayObjects<Integer>();
for (int i = 0; i < 10; i++) list.addLast(i);
for (Integer i: list) {
System.out.println("Iterating over list! Next element is " + i);
}
You should do something like this, assuming that your actual size is 1 when you add your first element BUT the position will be 0 because it's the first position of the array.
public boolean addObj(E obj){
if(actualSize == maxCapacity){
return false;
}
array[actualSize--] = obj;
return true;
}
I changed the return value to return false if there is no positions left in the array (considering that you won't remove any object in the middle).
Why do you need an array? Why not going with a List?
public class ArrayObjects<E> implements SomeImp<E>{
private List<E> list;
private int maxCapacity;
public ArrayObjects(){
maxCapacity = 10;
list = new ArrayList<E>();
}
public boolean addObj(E obj){
if(list.size() == maxCapacity){
return false;
}
list.add(obj);
return true;
}
}
See that using a List you won't have to deal with the actualSize.
EDIT: as Smac89 points out, it makes no sense to use a list. But keep in mind you will have to find an empty position if the array is not full.

Java Arrays[] - Assigning Specific Elements in a For Loop to Certain Values

I was attempting to write some code for a program in BlueJ (Java) that lists bags and adds and removes items from those bags, that sort of thing. Then I got stuck in the first class; I couldn't get to add an item to the bag properly as you can notice below in the addItem() method; it keeps adding String s to every null element in the array rather the first encountered. Any help would be tremendously appreciated.
Best wishes & many thanks,
Xenos
public class Bag1 {
private String[] store; // This is an array holding mutlitple strings.
public Bag1(int storageCapacity) {
store = new String[storageCapacity];
} // That was the primitive array constructor.
public boolean isFull() {
boolean full = true;
for(int i = 0; i < store.length; i++) {
if(store[i] == null) {
full = false;
}
}
return full;
} // The method above checks if the bag is full or not, and returns a boolean value on that basis.
public void add(String s) {
for(int i = store.length; i >= 0; i--) {
if(store[i] == null) {
store[i] = s;
}
}
}
}
You should exit the loop after finding the first empty spot :
public void add(String s)
{
for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
if(store[i]==null) {
store[i] = s;
break;
}
}
}

Java - Need help to solve a bug

I am currently learning Java and for my inner classes practice, I played aroud the following code:
public class DataStructure {
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// Print out values of even indices of the array
DataStructureIterator iterator = this.new EvenIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
interface DataStructureIterator extends java.util.Iterator<Integer> { }
// Inner class implements the DataStructureIterator interface,
// which extends the Iterator<Integer> interface
private class EvenIterator implements DataStructureIterator {
// Start stepping through the array from the beginning
private int nextIndex = 0;
public boolean hasNext() {
// Check if the current element is the last in the array
return (nextIndex <= SIZE - 1);
}
public Integer next() {
// Record a value of an even index of the array
Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
// Get the next even element
nextIndex += 2;
return retValue;
}
public void setNextIndex(int i){
nextIndex=i;
}
}
public void print(DataStructureIterator iterator) {
// Print out values of odd indices of the array
//iterator = this.new EvenIterator();
iterator.setNextIndex(1);//**This line giving me compiler error that setNextIndex is undefined for type DataStructure.DataStructureIterator **
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
public EvenIterator createNewObject(){
return this.new EvenIterator();
}
public static void main(String s[]) {
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
System.out.println("Even Index");
ds.printEven();
System.out.println("Odd Index");
ds.print(ds.createNewObject());
}
}
I am passing a EvenIterator object to the method print(DataStructureIterator), as far as I know a iterator can refer to a EvenIterator object(since DataStructureIterator is a implemented by EvenIterator), though hasNext() and setNextIndex(int) are in the same class the reference iterator is able to access only hasNext.
How can I fix this bug?
Even though you are passing EvenIterator to the method print(DataStructureIterator), it is silently getting casted into DataStructureIterator. So if the setNextIndex(int) method is not declared in DataStructureIterator, you will not be able to access it.
The print method know its parameter is a DataStructureIterator. Is the method setNextIndex declared in that interface? If not, you must add it.

Categories