Question

Can someone please explain this piece of java code line by line as to what they...

Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments).

Code:

import java.util.*;

public class Array
{
private Integer[] array; // NOTE: Integer is an Object.

Array()
{
    super();
    array = new Integer[0];
}

Array(Array other)
{
    super();
    array = other.array.clone(); // NOTE: All arrays can be cloned.
}

void add(int value)
{
    Integer[] newarray = new Integer[array.length+1];
    int i;
    for (i=0; i < array.length; ++i)
      newarray[i] = array[i];
    newarray[i] = value;
    array = newarray;
    return;
}

public Iterator<Integer> iterator()
{
    class Iter implements Iterator<Integer>
    {
      int pos = 0;

      public boolean hasNext()
      {
        return pos < array.length;
      }

      public Integer next() throws NoSuchElementException
      {
        if (hasNext())
        {
          Integer retval = array[pos];
          ++pos;
          return retval;
        }
        else
          throw new NoSuchElementException();
      }

      public void remove() throws UnsupportedOperationException
      {
        throw new UnsupportedOperationException();
      }
    }
    return new Iter();
}

public static final void main(String[] args)
{
    Array a = new Array();
    a.add(1);
    a.add(2);
    a.add(3);
    for (Iterator<Integer> i=a.iterator(); i.hasNext(); )
    {
      Integer value = i.next();
      System.out.println(value);
    }
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Feel free to post a comment if you have any queries (attaching screenshots of the code below if you'd like to know the meaning of a specific line)

// Upvote the answer if you like it!

import java.util.*;

public class Array {
private Integer[] array; // NOTE: Integer is an Object.
// Integer is an object, it hasn't been initialized till now
// Only a reference named "array" is created

Array() {
// This just creates a new object
// super() is used to call the constructor of the parent class explicitly
// Every class in Java inherits from Object class
super();
// An integer array is made of length 0
array = new Integer[0];
}

// This is a copy constructor
Array(Array other) {
super();
// It just clones the array that we have, please note the lowercase 'a'
// This constructor can be called in main as:
// Array b = new Array(a);
// After we have defined the array a that is (in main)
array = other.array.clone(); // NOTE: All arrays can be cloned.
}

// This method is used to append values to the array
void add(int value) {
// Everytime this method is called a new array is created with length 1 greater than the previous array
Integer[] newarray = new Integer[array.length + 1];
int i;
// Each element in the old array is copied to the new array
// This can be expensive because consider you have a million elements and a million iterations will take place when
// adding a new element
for (i = 0; i < array.length; ++i)
newarray[i] = array[i];
  
// Append the value to be added at the end
newarray[i] = value;

// This is the most important step, to make changes to the original array, we just assign the value
array = newarray;
  
// return back to calling function when done
return;
}

// Create a method called iterator() which return an Iterator<Integer>
public Iterator<Integer> iterator() {
// Define a class inside it which is just used to override the default behaviour of the Iterator
class Iter implements Iterator<Integer> {
// pos is used to store the current position of the iterator
int pos = 0;

// Check if there are elements ahead of the current position of the iterator
// we return pos < array.length which is a boolean value which is true if the condition is satisfied
public boolean hasNext() {
return pos < array.length;
}
  
// get the element from the position
// and increment the position by 1
// "next" is in terms of the Iterator, it just moves onto the next element
// while also returning the current element
public Integer next() throws NoSuchElementException {
// Check if there are more elements
if (hasNext()) {
// save the value to be returned to a variable
Integer retval = array[pos];
++pos;
return retval;
} else
// if no elements are ahead of pos
throw new NoSuchElementException();
}
  
// This just overrides the method remove() from Iterator
// and throws an exception if it is called
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
// return an object of the Iter class that you just defined
return new Iter();
}

public static final void main(String[] args) {
// Create an object of Array class
Array a = new Array();

// Add element elements to the array
a.add(1);
a.add(2);
a.add(3);

// Iterate over the array using an iterator which in simple terms is like an index
// a.iterator() means that we are calling our own "iterator" method
// inside the iterator method, we have defined a class name Iter which implements the Iterator interface
for (Iterator<Integer> i = a.iterator(); i.hasNext();) {
// This part is only executed if there are more elements in the Array
// We have seen 0 elements till now so i.next() returns the first element which is at index 0 [for first iteration]
Integer value = i.next();
// value = 1 [for first iteration]
// print the value
System.out.println(value);
}
}
}

C secant.cpp neuralNetwork.c Cplayers.cpp Array.java . secant.h G secant test.cpp Array java Array Array() import java.util.*C players.cpp C secant.cpP Array.java . :neuralNetwork.c secant.h G secant test.cpp Array java Array Array) = array[i] ; newaC secant.cpp C secant test.cpp C players.cpP Array.java . :neuralNetwork.c secant.h Array java Array Array) else 72 // if no

Add a comment
Know the answer?
Add Answer to:
Can someone please explain this piece of java code line by line as to what they...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please help complete the items marked TODO in the code and get the tests to pass:...

    Please help complete the items marked TODO in the code and get the tests to pass: import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestIterator { private List<Integer> list; // See the Java List Interface documentation to understand what all the List methods do ... @Before public void setUp() throws Exception { list = new ArrayList<Integer>(); // TODO also try with a...

  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • Consider the following class definition class FibSequence implements Iterablexnteger public Iterator<Integer> iterator) return new FibIterator); private class FibIterator implements Iterator&lt...

    Consider the following class definition class FibSequence implements Iterablexnteger public Iterator<Integer> iterator) return new FibIterator); private class FibIterator implements Iterator<Integer> f //complete this You are required to create an inner class in the FibSequence class. The inner class should be called FibIterator. It implements the Iterator<Integer> interface and implements the hasNext() and the next() methods. The iterator iterates through the Fibonacci sequence. The Fibonacci sequence is a series of numbers where a number is the sum of previous two numbers....

  • Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac...

    Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...

  • Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

    Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list using bubble sort Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods. import java.lang.Comparable; import java.util.*; public class IteratorExercise {       public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {        // first line to start you off        ListIterator<E> iit = c.listIterator(), jit;...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • ANNOTATE BRIEFLY LINE BY LINE THE FOLLOWING CODE: package shop.data; import junit.framework.Assert; import junit.framework.TestCase; public class...

    ANNOTATE BRIEFLY LINE BY LINE THE FOLLOWING CODE: package shop.data; import junit.framework.Assert; import junit.framework.TestCase; public class DataTEST extends TestCase { public DataTEST(String name) { super(name); } public void testConstructorAndAttributes() { String title1 = "XX"; String director1 = "XY"; String title2 = " XX "; String director2 = " XY "; int year = 2002; Video v1 = Data.newVideo(title1, year, director1); Assert.assertSame(title1, v1.title()); Assert.assertEquals(year, v1.year()); Assert.assertSame(director1, v1.director()); Video v2 = Data.newVideo(title2, year, director2); Assert.assertEquals(title1, v2.title()); Assert.assertEquals(director1, v2.director()); } public void testConstructorExceptionYear()...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Computer Science - Java Explain the code step by step (in detailed order). Also explain what...

    Computer Science - Java Explain the code step by step (in detailed order). Also explain what the program required. Thanks 7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] -...

  • This wont take you more than 15 mins. Comple the two method and besure to test...

    This wont take you more than 15 mins. Comple the two method and besure to test with Junit test that provided below. toArray() -- this method returns a newly allocated array containing the elements in the multiset. The array this method returns must only contain the elements in the multiset and not any nulls or other values that are stored in the backing store, but are not in the multiset. fromArray(E[] arr) -- this method updates the multiset so that...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT