Remove method of array

Implement the following method in the class Project 11 to return a new array that contains all the elements of the array a not in b.
Public static int [] remove (int[] a, int[] b)
For example, if the array a is {5,3,2,7,1} and the array b is {8,2,5} the remove method should return the array {3,7,1}.
Im having trouble getting it run correctly, and i think my problem is with the remove method that i made
//heres my code
public static void main(String[]args) {
int [] first = {2,5,4,1,9};
int [] second = {5,10,8,1};
int duplicate =0;
for (int i = 0; i < first.length; i++) {
               for (int j =0; j < second.length; j++){
                    if (first[i] == second[j])
                         duplicate++;
                    remove(first, second);
System.out.println(first);
public static int [] remove(int[] a, int []b){
for(int i = 0; i < a.length; i++) {
if(a[i] == b) {
int[] c = new int[a.length - 1];
return c;
return a;

im having trouble with the remove method. im suppose to return a new array that contains all the elements of the array a not in b.
Public static int [] remove (int[] a, int[] b)
For example, if the array a is {5,3,2,7,1} and the array b is {8,2,5} the remove method should return the array {3,7,1}.
//heres my code
public static void main(String[]args) {
int [] first = {2,5,4,1,9};
int [] second = {5,10,8,1};
int duplicate =0;
for (int i = 0; i < first.length; i++) {
for (int j =0; j < second.length; j++){
if (first == second[j])
duplicate++;
remove(first, second);
System.out.println(first);
public static int [] remove(int[] a, int []b){
for(int i = 0; i < a.length; i++) {
if(a[i] == b) {
int[] c = new int[a.length - 1];
return c;
return a;

Similar Messages

  • Remove method: push in the right direction

    Hello everybody. I am new to java and programming all together ( i have been programming for about 3 weeks or so). I am sorry if the question is simple. I seem to be having a problem with remove function.
    Basically I have class Task(which has an ID, brief description, dueDate etc...). I also have a task TaskList as well as a class Date . The taskList has attributes an array of type Task with a length of 10. It also has methods to add, remove tasks as well as display the arrays contents. The remove method is what is causing me problems.
    My general thinking was to find the arraycell containing the reference that points to the taskId that is to be removed. Afterwards I wanted to assign a null value to the cell containing the task to be removed. Then i would begin by swapping references until the null value is in a way where the array has no wholes in it.
    I have tried different variations of the same logic but either it does absolutely nothing, either I get a nullpointer exception. I am not looking for an explicit answer, just a nudge in the right direction. Is the general idea I proposed earlier worth anything. Can I affect a null value to an arraycell containing a reference to an object.
    Thank you in advance for any help.
    P.S: Again I apologize, for I know this must be a question that keeps coming up over and over...
    Oh, before I forget, are there any good textbooks that explain ina detailed manner class relationships, particularly dependancy, aggregation and inheritance.

    Why not use a List instead? Lists are dynamic, i.e. they can add or remove
    elements anywhere, closing the gap (i.e. there's no need to stuff nulls in there).
    Something like this:public class TaskList {
       private List l= new ArrayList();
       public void add(Task t) { l.add(t); }
       public boolean remove(Task t) { return l.remove(t); }
       // all the other functionality you want goes here ...
    }kind regards,
    Jos

  • I need help with my remove method on a BST!

    Guys I need some help here, I have to create a remove method for a BST and below is my code:
    public boolean remove(OrderedMap map, K keyOfelementToRemove) {
              boolean result = false;
              if (root == null)
                   result = false;
              else {
                   MapNode curr = root;
                   MapNode prev = root;
                   while (curr.key.equals(keyOfelementToRemove) == false) {
                        prev = curr;
                        if (keyOfelementToRemove.compareTo(curr.key) < 0)
                             curr = curr.left;
                        else if (keyOfelementToRemove.compareTo(curr.key) > 0)
                             curr = curr.right;
                        if (curr == null)
                             break;
                   if (curr == null)
                        return result;
                   else if (curr == root && curr.left == null)
                        root = root.right;
                   else if (curr.left == null) {
                        if (curr.right == null)
                             curr = null;
                        else if (curr == prev.left)
                             prev = curr.right;
                        else if (curr == prev.right){
                             prev = curr.right;
                   else if (curr.left != null) {
                        MapNode temp = curr.left;
                        while (temp.right != null)
                             temp = temp.right;
                        K change = temp.key;
                        temp = null;
                        curr.key = change;
              size--;
              return result;
         }the algorithm that my instructor provides is:
    private boolean remove( BinaryTreeNode t, Comparable elementToRemove )
    Set result to false
    Traverse the tree t until elementToRemove is found. Use curr and prev to find the element
    leaving curr referring the node you want to remove. It may be the case that curr is null indicating
    that elementToRemove was not found. Now there are four cases to consider :
    Case 1: Not found
    return result (false)
    Case 2: The root is to be removed, but it has no left child.
    root = root's right subtree (assuming root refers the the root node in your BST)
    Case 3: The node is further down tree with no left child. Now must adjust one of the parent's links
    if curr is on the left side of prev,
    move parent's left link down to down to curr's right child
    else
    curr is on the right side of prev, so move parent's right down to down to curr's right child
    Case 4: curr has a left child.
    We can no longer ignore the left subtree. So find the maximum in the left subtree and
    move that object to the node referenced by curr . Then eliminate the maximum in the
    left subtree, which is now being reference from the original node to remove.
    however for case 3 and 4 it doesn't work, can someone please tell me why? I don't know where I made a mistake and I tried finding it but I still dont know

    I am sorry about the double post. I'll try not to do this again. My problem here seems to be that prev and curr aren't updating the BST outside this method, which means that it only changes locally but not permanently. I will post the code of the other headings:
    public class OrderedMap<K extends Comparable<K>, V> {
         private class MapNode {
              // Links to other BSTs
              private MapNode left;
              private MapNode right;
              ArrayList<V> temp1 = new ArrayList<V>();
              // The references to the key/value pair of the mapping
              private K key;
              @SuppressWarnings("unused")
              private V value;
              public MapNode(K theKey, V theValue) {
                   key = theKey;
                   value = theValue;
                   left = null;
                   right = null;
         } // end class MapNode
         private MapNode root;
         private int size;
         public OrderedMap() { // Create an empty tree
              root = null;
              size = 0;
         public int size() {
              return size;
         }

  • Howto call the @Remove method of a stateful session bean after JSF page ...

    I use EJB3, JPA, JSF in my web application. There are 2 database tables: Teacher and Student. A teacher can have many (or none) students and a student can have at most 1 teacher.
    I have a JSF page to print the teacher info and all his students' info. I don't want to load the students' info eagerly because there's another JSF page I need to display the teacher info only. So I have a stateful session bean to retrieve the teacher info and all his students' info. The persistence context in that stateful session bean has the type of PersistenceContextType.EXTENDED. The reason I choose a stateful session bean and an extended persistence context is that I want to write something like this without facing the lazy initialization exception:
    <h:dataTable value="#{backingBean.teacher.students}" var="student">
        <h:outputText value="${student.name}"/>
    </h:dataTable>Because my session bean is stateful, I have a method with the @Remove annotation. This method is empty because I don't want to persist anything to the database.
    Now, my question is: How can I make the @Remove method of my stateful session bean be called automatically when my JSF page finishes being rendered?

    Philip Petersen wrote:
    I have a few questions concerning the EJB remove method.
    1) What is the purpose of calling the remove method on stateless session
    bean?There isn't one.
    >
    2) What action does the container take when this method is called?It checks that you were allowed to call remove (a security check) and then
    just returns.
    >
    3) What happens to the stateless session bean if you do not call the remove
    method?Nothing
    >
    4) Is it a good practice to call the remove method, or should the remove
    method be avoided in the case of stateless session beans?
    Personally, I never do it.
    -- Rob
    >
    >
    Thanks in advance for any insight that you may provide.
    Phil--
    AVAILABLE NOW!: Building J2EE Applications & BEA WebLogic Server
    by Michael Girdley, Rob Woollen, and Sandra Emerson
    http://learnWebLogic.com
    [att1.html]

  • What types of sort performed by sort method of Array class ?

    I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
    Can anybody tell me what types of sort performed by sort method of Array class?

    I'm pretty sure that in eariler versions (1.2, 1.3
    maybe?) List.sort's docs said it used quicksort. Or I
    might be on crack.You are actually both correct, and wrong :)
    From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
    "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
    So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
    "Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
    Your memory serves you well :)
    /Kaj

  • Need help with a remove method..

    Hello. I'm getting started on a project here to implement a recursive remove method that will remove any number from a list. I was given a test that the method must pass, but I'm having some trouble getting started. This is my second interaction with the idea of recursion and it's a bit difficult for me.
    Here is the test I'm writing the method for:
    public void testRemove() {
              int element=0;
              boolean inList = false;
              for (int i = -10; i < 11; i++)list.insert(i);
              int numElements = list.length();
              list.remove(element);
              for (int e : list) {
                   if ( e == element ) inList = true;
              assertTrue(!inList && (list.length()==(numElements-1)));
              element = -10;
              inList = false;
              list.remove(element);
              for (int e : list) {
                   if ( e == element ) inList = true;
              assertTrue(!inList && (list.length()==(numElements-2)));
              element = 10;
              inList = false;
              list.remove(element);
              for (int e : list) {
                   if ( e == element ) inList = true;
              assertTrue(!inList && (list.length()==(numElements-3)));
              //does remove work when element's value greater than value of last item in list
              element = 20;
              inList = false;
              list.remove(element);
              for (int e : list) {
                   if ( e == element ) inList = true;
              assertTrue(!inList && (list.length()==(numElements-3)));
              //does remove work when element's value less than value of first item in list
              element = -20;
              inList = false;
              list.remove(element);
              for (int e : list) {
                   if ( e == element ) inList = true;
              assertTrue(!inList && (list.length()==(numElements-3)));
              System.out.printf("%s\n", "testRemove " + list.toString());
         }Now, clearly I need to test whether or not the number being removed is in the list (too low/too high), but I'm stuck trying to implement this.
    If anyone can give me any ideas or direction it would be greatly appreciated.

    Thanks for the quick reply, from what I had gathered and what you posted I'm starting to see where I need to go from here. I had gotten as far as if list is null return null, and the cod that you posted makes sense, but implementing it into the source code I already have will be troubling for me. The code as you presented it I have no trouble understanding, for example:
    if (list.data == data) return list.next;
    list.next=remove(list.next, data);Is clear to me, however I don't know how to implement that into my code. This is the code for the insert method:
         private Node<ElementType> insertp(Node<ElementType> list, ElementType element) {
              if ( (list == null) || ( element.compareTo(list.getElement() ) < 0 ) ) {
                   // test for insert at head or before current node
                   Node<ElementType> newNode = new Node<ElementType>(element, null);
                   newNode.setNext(list);
                   return newNode;
              else if (list.getNext() == null) { // list with one element
                   Node<ElementType> newNode = new Node<ElementType>(element, null);
                   list.setNext(newNode);         // element goes at end
              else if ( element.compareTo(list.getNext().getElement()) < 0 ) { // insert after list
                   Node<ElementType> newNode = new Node<ElementType>(element, list.getNext());
                   //newNode.setNext(list.getNext());
                   list.setNext(newNode);
              else {
                   insertp(list.getNext(), element); // find insertion point
              return list;
         }I'm still struggling to understand all of the code there. the element.compareTo() and everything. If you (or some one else) can explain to me what is going on with those methods, I may be able to implement it myself. Also, this may be of some use, these are the methods I have available to me:
    public class Node<E> {
      // Instance variables:
      private E element;
      private Node<E> next;
      /** Creates a node with null references to its element and next node. */
      public Node() {
        this(null, null);
      /** Creates a node with the given element and next node. */
      public Node(E e, Node<E> n) {
        element = e;
        next = n;
      // Accessor methods:
      public E getElement() {
        return element;
      public Node<E> getNext() {
        return next;
      // Modifier methods:
      public void setElement(E newElem) {
        element = newElem;
      public void setNext(Node<E> newNext) {
        next = newNext;
      public String toString() {
           return element.toString();
    }

  • What happens if you don't define '@Remove' method for Stateful SessionBean?

    Hi,
    I'm new to ejb3.
    I've noticed that the spec doesn't force you to define a "@Remove" method on a stateful Session bean... which seemed a bit weird/dangerous to me...
    Would anyone please happen to know:
    1. Is there a special treatment for Staeful SB's that don't have "@Remove"? Like, for examle, will the container destroy the session automatically at some point (after each remove invocation ? After a fixed timeout ? etc).
    2. And what if the programmer defined '@Remove' but neglected to call it from the client ? Are there different rules ? Session timeout ?
    Thanks a lot !

    There are always ways in which the container can decide to remove a Stateful Session Bean(SFSB) that are completely independent of whether a client explicitly calls a remove method. The container can choose to remove a SFSB because it has timed out. The actual time out is typically configurable, much like HttpSession timeout. The container can also remove a SFSB due to a system exception generated from one of its methods.
    @Remove methods merely expose an application-specific way to force the removal of a SFSB. They are not required to be defined and even if defined are not required to be invoked.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Bad logic in NamedCache remove method?

    Why does the remove method in a NamedCache invoke the load method in the CacheStore in a distributed cache? Why force a database load call for the object if it doesn't exist in the cache only to immediately remove it?
    Edited by: 786216 on Aug 3, 2010 10:07 AM

    Hi 786216,
    The reason for that comes to the contract of the java.util.Map#remove(Object) method that NamedCache inherits is to return the "old" value. Basically, the net effect should be the same as:
    oValue = map.get(oKey);
    map.removeBlind(oKey); // pretend such a method exists
    return oValue;The good news is that the removeBlind() method does exists. It looks like:
    map.keySet().remove(oKey);and will not cause the store.load() operation to occur.
    Regards,
    Gene

  • Linked list remove method???

    hi i have made a remove method in a publication contaqiner class which links to the publicationmain.The problem is that when i run the program and try to delete a publication i get the message
    "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:1, Size:1 at java.util.LinkedList.entry<LinkedList.java:348>
    java.util.LinkedList.remove<LinkedList.java:338>
    PublicationContainer.remove<publicationcontainer.java>
    publicationmain.main<publicationmain.java>"
    What does this mean?how do i fix it so my delete method workks?can ssomeone please show me in my code???thanxs
    //this is in the publication container
    public void remove(int PubID)
    PubList.remove(PubID);
    //this is in the publicationmain class
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);

    The remove(int index) method that you are calling will try and remove the item at the index you specify.
    As the index starts at zero, if you want to remove the first element then you have to call remove(0). Calling remove(1) is beyound the possible indexes in the list, so you will get the exception thrown.
    HTH
    Chris
    hi i have made a remove method in a publication
    contaqiner class which links to the
    publicationmain.The problem is that when i run the
    program and try to delete a publication i get the
    message
    "Exception in thread "main"
    java.lang.IndexOutOfBoundsException: Index:1, Size:1
    at java.util.LinkedList.entry<LinkedList.java:348>
    java.util.LinkedList.remove<LinkedList.java:338>
    PublicationContainer.remove<publicationcontainer.java>
    publicationmain.main<publicationmain.java>"
    What does this mean?how do i fix it so my delete
    method workks?can ssomeone please show me in my
    code???thanxs
    //this is in the publication container
    public void remove(int PubID)
    PubList.remove(PubID);
    //this is in the publicationmain class
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);

  • Remove methods in Entity EJBs

    Hi,
    I have a entity EJB with following methods:
    findByPrimaryKey(PK)
    create(PK)
    get and set methods
    I wanna add a remove method which will take the PK and delete the record for
    me.
    Please tell me the changes I have to incorporate. and How do i do it. I am using VA 3.5 and WAS 3.5
    Thanx & Regards
    Ravi Mittal

    hi,
    after adding access bean & generating deployed code you have to add remove method in Access Bean by yourself. remove(object) is in EJBhome interface.
    you have to pass object of key class. so add empty remove() in acees bean. instantiate ur key class there & call remove(keclassobject) method. I think it will help you.
    -priya

  • How to call java method having array as argument from c++ ?

    Hello sir,
    how to call java method having array as arguments from c++;
    here is java code which is called from c++
    class PQR {
         public void xyz(int[] ia) {
         System.out.println("hi");
              for (int i = 0; i < ia.length; i++)
                   System.out.println(ia);
    suppose all jvm invocation is done...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    For someone well versed in java, C++ and JNI although tedious that should be obvious.
    For someone not well versed in all three it is going to be very difficult.
    Even for someone that does have knowledge in all of those areas coming up with a C++ interface that reflects that functionality in a dynamic way such that anyone is will to use it is going to be quite an adventure.
    At any rate to start building it you do exactly the same thing that you would in java.
    1. Extract everything in the jar via the zip package
    2. For each found instance extract all of the methods, return types, parameters, etc and build a description tree for each class.
    Doing all of that in C++ is going to take a LOT of code. If someone wanted an estimate from me it would take me 6 months to do it. And before I would even attempt it I would get them to explain to me in detail exactly how they thought they were going to use it when I was done because I can't see any reasonable way to do that.
    I left out the description tree itself. I suppose you could duplicate the entire reflection api in C++.
    Now perhaps if it was much, much more constrained, like to only those classes that implement a single interface then that would be more reasonable.

  • Why doesn't reflection reveal the clone() method in arrays?

    I was surprised to discover that the following code does not reveal the method "clone()", even though you can call "clone()" on an Object[]. Can anyone explain why this is? I was hoping to use the Reflect API to clone an arbitrary object if it was Cloneable, and to throw an Exception otherwise. How can I do this?
    import java.lang.reflect.Method;
    public class Test {
         public static void main(String[] args) throws Exception {
              Object x;
              //pick a class
              x = new Object[] {};
              //is it Cloneable?
              System.out.print("The class " + x.getClass().getCanonicalName() + " is ");
              if(!(x instanceof Cloneable)) System.out.print("NOT ");
              System.out.println("Cloneable");
              System.out.println("-------");
              //what methods are available?
              Method[] meths = x.getClass().getMethods();
              for(Method m : meths) {
                   System.out.println(m.getName());
              System.out.println("-------");
    }

    Just to clarify. I know that clone() is protected in Object, but it is certainly a public method in array objects such as int[], float[], Object[] etc. Test: call clone() on any of these objects! Also, I realize that Cloneable does not itself guarantee the method clone(). Nevertheless, if you take a regular Cloneable object, such as a String, then typically, if you ran myObject.getClass().getMethods() on that object, you'd find the method clone() in the resulting list. i.e., that Class has overwritten Object's protected clone() method with a public clone() method. So since int[], float[] and all the rest have a clearly public clone() method, then why doesn't myFloatArray.getClass().getMethods() show me a method called "clone"? I guess it would have to have something to do with the fact that arrays are funny kinds of classes that are not properly handled by the Reflection API, but is it on purpose that clone() isn't available?

  • Differenece between remove method

    Hi
    what is difference between Collection.remove() and
    iterator.remove() method.
    Why can't we use Collection.remove() method to remove a element.
    Pls clarify
    Thanks in Advance.
    ur's
    malli

    When you use Collection.remove() while using Iterator, you will get ConcurrentModificationException.

  • FATAL ERROR in native method: Non-array passed to JNI array operations

    After stepping up to JDK 1.4.2 we started getting a hotspot error, I added -Xcheck:jni and it yielded the above error which was not existent in JDK 1.4.1 and for the life of me I cannot find out whats wrong:
    Native method dec:
    private native byte[] cost(final byte[] byte_array,
    final double minCostPerMeter,
    final int costFuncSelection,
    final double maxCostThreshold);
    Method call:
    ByteArrayInputStream
    inputByteStream = new ByteArrayInputStream(
    cost(output_byte_stream.toByteArray(),
    minCostPerMeter,
    costFunctionSelection.length,
    maxCostThreshold));
    An array is being passed I have no idea why it is complaing about the method call.
    Any help would be appreciated.
    -R

    What happens if you remove all the code from the JNI method - so it just calls and then returns?
    If it still occurs then I would expect that you have a memory problem in a piece of code before this one. Such problems can have no impact when run in one environment but cause failures in another becomes some other legitimate piece of data moved.
    If it doesn't then I would expect that the problem is in the method itself and not the call.
    It could be some odd VM problem so trying a different version of 1.4.2 might help (but in of itself would not eliminate the possibility that you have a memory problem.)

  • Error with declaring a method with array variable

    Hi,
    I had implemented this:
    import java.awt.*;
    import javax.swing.*;
    public class Oefening1
         public static void main(String args[])
              int array[]= new int[10];
              int getal;
              JTextArea outputArea = new JTextArea();
              Container container = getContentPane();
              container.add(outputArea);
              public void invoerRij(int array[10])
                   output +=" ";
                   for(int counter = 0; counter <10;counter++){
                        output +="Geef een getal in"+"\n"+array[counter]+"\n";
                        outputArea.setText(output);
    I had comilated this code while the compiler gave errors like these:
    A:\Oefening1.java:15: illegal start of expression
              public void invoerRij(int array[10])
    ^
    A:\Oefening1.java:24: ';' expected
    ^
    A:\Oefening1.java:12: cannot resolve symbol
    symbol : method getContentPane ()
    location: class Oefening1
              Container container = getContentPane();
    ^
    3 errors
    Tool completed with exit code 1
    Now i have read my book and finded out that the declaration of a method always starts with public.
    Can anyone halp me solving these probs? Thanks
    Crazydj1

    The problem is that you didn't close the previous method definition.
    Compiler error messages (in any language) often mistakenly report false errors on perfectly valid code immediately following the actual error.
    When you post code on these forums, please wrap in in &#91;code]&#91;/code] tags.

Maybe you are looking for