import java.io.*; import java.util.*; import java.util.Iterator; /* * Laget i coderpad -> litt spesiell syntax */ class Solution { public static void main(String[] args) { VaarArray va = new VaarArray<>(10); for(int i = 0; i < 10; i++){ va.settInn(i * 10); } if(va.fjernFraIndex(11) == false){ System.out.println("Index is out of bounds!"); } System.out.println("Printer array:"); for(Integer v : va){ System.out.println("Verdi: " + v); } System.out.println("Fjerner noen plasser..."); va.fjernFraIndex(0); va.fjernFraIndex(5); va.fjernFraIndex(6); va.fjernFraIndex(9); System.out.println("\nPrinter array:"); for(Integer v : va){ System.out.println("Verdi: " + v); } } } @SuppressWarnings("unchecked") class VaarArray implements Iterable { T [] arr; public VaarArray(int strl) { arr = (T[]) new Object[strl]; } //Finner ledig plass og setter inn. Hvis det er plass returneres true, //hvis det er fullt returneres false public boolean settInn(T elem){ for(int i = 0; i < arr.length; i++) { if (arr[i] == null) { arr[i] = elem; return true; } } return false; } //Returnerer true dersom det var mulig ? fjerne, false ellers. public boolean fjernFraIndex(int n) { if (n < 0 || n > arr.length - 1){ return false; } arr[n] = null; return true; } public Iterator iterator(){ return new ArrayIterator(); } private class ArrayIterator implements Iterator{ private int pos = 0; public boolean hasNext() { for(int i = pos; i < arr.length; i++) { if (arr[i] != null) {return true;} } return false; } public T next(){ for(int i = pos; i < arr.length; i++) { if (arr[i] != null) { pos++; return arr[i]; } //Vi hadde glemt ? ?ke pos for tomme plasser!!! pos++; } return null; } } }