Implementing an ArrayList as a Primitive Array. Plzzz Help a Newbie!!!

Hi I am a newbie to Java,
I have the following question, could someone please demonstrate some code to answer it?...
Q)
The Java class ArrayList uses a primitve array as its internal data structure and provides methods to access the array elements.
Write a implentation of a basic version of ArrayList providing methods to get, set, insert and delete elements. It should be possible to insert and delete at any position within the ArrayList. The methods should throw exceptions as necessary. Include one or more appropriate constructors.
Thanks in advance
Carl

Hi I am a newbie to Java,
I have the following question, could someone please
demonstrate some code to answer it?...
Q)
The Java class ArrayList uses a primitve array as its
internal data structure and provides methods to
access the array elements.
Write a implentation of a basic version of ArrayList
providing methods to get, set, insert and delete
elements. It should be possible to insert and delete
at any position within the ArrayList. The methods
should throw exceptions as necessary. Include one or
more appropriate constructors.
Thanks in advance
CarlNo it doesn't. It uses an object array. The question itself demonstrates that the author was either sleepy or not very knowledgeable to begin with as they either consider an array of objects a "primitive array" or they think all arrays are primitives.
Regardless, what I suspect they want from you is more or less a Collection backed by an array. For an example of one look at ArrayList's source code to begin with.

Similar Messages

  • Trouble with primitive arrays and casting, lesson 521

    hi everyone!
    there is a problem i discovered right now - after years with java where was no necessity to do this.....
    and i'm shure this must have been the topic already, but i couldn't find any helpful resource :-/
    right here we go:
    1. an array is a (special) kind of object.
    2. there are "primitive" arrays and such containing references to objects. of course - and i imagine why - they are treated differently by the VM.
    3. then both are - somehow - subclasses of Object. whereas primitive types are not really, primitive-arrays are. this is hidden to the programmer....
    4. any array can be "pointed" at via local Object variable, like this:
    Object xyz = new int[6];
    5. arrays of Objects (with different dimensions) can be casted, like this:
      Object pointer = null;
      Object[]   o  = new SomeClass[42] ;
      Object[][] oo = new OtherClass[23] [2] ;
      Object[][][] ooo = new OtherClass[23] [2] [9] ;
      o = oo = ooo;     // this is save to do,
                                   //because "n-dimensional" object-arrays
                                  // are just arrays of  other arrays, down to simple array
    pointer = o;         // ok, we are referencing o via Object "pointer"6. but, you cannot do this with primitive types:
      int[]  i1 = new int [99] ;
      int[][] i2 = new int [1] [3] ;
      i1 = i2                  // terror: impossible. this is awful, if you ask me.
                                   // ok, one could talk about "special cases" and
                                   // "the way the VM works", but this is not of interest to me as
                                   // a programmer. i'm not happy with that array-mess!
      pointer = i2;       // now this is completely legal. i2, i1 etc is an object!7. after the preparation, let's get into my main trouble (you have the answer, i know!) :
    suppose i have a class, with methods that should process ANY kind of object given. and - i don't know which. i only get it at runtime from an unknown source.
    let's say: public void BlackBox( Object x );
    inside, i know that there might be regular objects or arrays, and for this case i have some special hidden method, just for arrays... now try to find it out:
    public void BlackBox( Object x )
      if ( x == null)
           return;
       Class c = x.getClass();
       if ( c.isArray() )
              // call the array method if it's an array.........
              BlackBoxes(     (Object [] )  x );         // wait: this is a cast! and it WILL throw an exception, eventually!
              return;
       else
               DoSpecialStuffWith( x );
    }ok ? now, to process any kind of array, the special method you cannot reach from outside:
    private void BlackBoxes( Object[] xs )
       if ( xs != null )
            for ( Object x : xs )
                 BlackBox( x );
    // this will end up in some kind of recursion with more than one array-dimension, or when an Object[] has any other array as element!this approach is perfectly save when processing any (real) Object, array or "multi-dimensional" arrays of Objects.
    but, you cannot use this with primitive type arrays.
    using generics wouldn't help, because internally it is all downcasted to Object.
    BlackBox( new Integer(3) ) ---- does work, using a wrapper class
    BlackBox( new Integer[3] ) ----- yep!
    BlackBox( 3 ) ---- even this!
    BlackBox( new int[42] ) ---- bang! ClassCastException, Object[] != int[]
    i'm stuck. i see no way to do this smoothly. i could write thousands of methods for each primitive array - BlackBox( int[] is ) etc. - but this wouldn't help. because i can't cast an int[][] to int[], i would also have to write countless methods for each dimension. and guess, how much there are?
    suppose, i ultimately wrote thousands of possible primitive-type methods. it would be easy to undergo any of it, writing this:
    BlackBox( (Object) new int[9] [9] );
    the method-signature would again only fit to my first method, so the whole work is useless. i CAN cast an int[] to Object, but there seems no convenient way to get the real array out of Object - in a generic way.
    i wonder, how do you write a serialisation-engine? and NO, i can't rely on "right usage" of my classes, i must assume the worst case...
    any help appreciated!

    thanks, brigand!
    your code looks weird to me g and i think there's at least one false assumption: .length of a multidimensional array returns only the number of "top-level" subarrays. that means, every length of every subarray may vary. ;)
    well i guess i figured it out, in some way:
    an int is no Object;
    int[ ] is an Object
    the ComponentType of int [ ] is int
    so, the ComponentType of an Object int[ ] is no Object, thus it cannot be casted to Object.
    but the ComponentType of int [ ] [ ] IS Object, because it is int [ ] !
    so every method which expects Object[], will work fine with int[ ] [ ] !!
    now, you only need special treatment for 1-dimensional primitive arrays:
    i wrote some code, which prints me everything of everything:
        //this method generates tabs for indentation
        static String Pre( int depth)
             StringBuilder pre = new StringBuilder();
             for ( int i = 0; i < depth; i++)
                  pre.append( "\t" );
             return pre.toString();
        //top-level acces for any Object
        static void Print( Object t)
             Print ( t, 0);
        //the same, but with indentation depth
        static void Print( Object t, int depth)
            if ( t != null )
                 //be shure it is treated exactly as the class it represents, not any downcast
                 t = t.getClass().cast( t );
                if ( t.getClass().isArray() )
                     //special treatment for int[]
                     if ( t instanceof int[])
                          Print( (int[]) t, depth);
                     // everything else can be Object[] !
                     else
                          Print( (Object[]) t, depth );
                     return;
                else
                    System.out.println( Pre(depth) + " [ single object:] " + t.toString() );
            else
                System.out.println( Pre(depth) + "[null!]");
        // now top-level print for any array of Objects
        static void Print( Object [] o)
             Print( o, 0 );
        // the same with indentation
        static void Print( Object [] o, int depth)
            System.out.println( Pre(depth) + "array object " + o.toString() );
            for ( Object so : o )
                    Print( so, depth + 1 );
        //the last 2 methods are only for int[] !
        static void Print( int[] is)
             Print( is, 0 );
        static void Print( int[] is, int depth)
            System.out.println( Pre(depth) + "primitive array object " + is.toString() );
            // use the same one-Object method as every other Object!
            for ( int i : is)
                 Print ( i, depth + 1 );
            System.out.println( "-----------------------------" );
        }now, calling it with
    Print ( (int) 4 );
    Print ( new int[] {1,2,3} );
    Print( new int[][] {{1,2,3}, {4,5,6}} );
    Print( new int[][][] {{{1,2,3}, {4,5,6}} , {{7,8,9}, {10,11,12}}, {{13,14,15}, {16,17,18}} } );
    Print( (Object) (new int[][][][] {{{{99}}}} ) );
    produces this fine array-tree:
    [ single object:] 4
    primitive array object [I@9cab16
          [ single object:] 1
          [ single object:] 2
          [ single object:] 3
    array object [[I@1a46e30
         primitive array object [I@3e25a5
               [ single object:] 1
               [ single object:] 2
               [ single object:] 3
         primitive array object [I@19821f
               [ single object:] 4
               [ single object:] 5
               [ single object:] 6
    array object [[[I@addbf1
         array object [[I@42e816
              primitive array object [I@9304b1
                    [ single object:] 1
                    [ single object:] 2
                    [ single object:] 3
              primitive array object [I@190d11
                    [ single object:] 4
                    [ single object:] 5
                    [ single object:] 6
         array object [[I@a90653
              primitive array object [I@de6ced
                    [ single object:] 7
                    [ single object:] 8
                    [ single object:] 9
              primitive array object [I@c17164
                    [ single object:] 10
                    [ single object:] 11
                    [ single object:] 12
         array object [[I@1fb8ee3
              primitive array object [I@61de33
                    [ single object:] 13
                    [ single object:] 14
                    [ single object:] 15
              primitive array object [I@14318bb
                    [ single object:] 16
                    [ single object:] 17
                    [ single object:] 18
    array object [[[[I@ca0b6
         array object [[[I@10b30a7
              array object [[I@1a758cb
                   primitive array object [I@1b67f74
                         [ single object:] 99
    -----------------------------and i'll have to write 8 methods or so for every primitive[ ] type !
    sounds like a manageable effort... ;-)

  • I have  a iphn 3gs running on ios 6.1.3  i buy it frm my frnd ..........n it has one prblm that safari mail n maps does't wrk it crashes all time when i try to run these ......plzzz help me what shoud i do ......i have tried reset many times bt it does't

    i have  a iphn 3gs running on ios 6.1.3  i buy it frm my frnd ..........n it has one prblm that safari mail n maps does't wrk it crashes all time when i try to run these ......plzzz help me what shoud i do ......i have tried reset many times bt it does't

    use a computer and restore the phone http://support.apple.com/kb/ht1414

  • Hi everyone,,i bought a used iphone 5 with iOs 7.0.3. i want to delete the icloud account and add mine. I have sent an e-mail to the current account being used in my iphone. How can i get rid of this account plzzz help me out

    Hi everyone,,i bought a used iphone 5 with iOs 7.0.3. i want to delete the icloud account and add mine. I have sent an e-mail to the current account being used in my iphone. How can i get rid of this account plzzz help me ou

    no i called the store owner from whom i bought it. he was like i will check in records and if there is something i will let u know...he was like send an e-mail its better so if it was stolen so the shopkeeper wouldnt let me to e-mail to the owner

  • Plzzz help me Jumping because of the antenna in iphone 5s

    plzzz help me >> Jumping because of the antenna in iphone 5s
    plz help me i from irann 2day ago Jumping because of the antenna

    Hi there , I bought the phone a month then suddenly jumped up and went to the phone antenna antenna on a search and did not even put my sim card out and then I had a message and phone repairman and he took the Restore and Restore to error -1 and the other came up and now I do not know what is in dfu yo I do not hit the phone rather then the water went into the antenna settings modem firmware was empty . now says  have a problem , anyone who has 'm handset , and the repair of put kept base -band phone. No way that 's true ? I 'm from Iran and the Persian language, I typed into Google translate to English mistake, please help me if you can
    iphone 5s 16 gb  me34LL/A 
    <Personal Information Edited by Host>

  • How to implement an independent static stub client ? Please, help

    Hi everybody!
    I'm using the jwsdp1.2 and i got the static stub tutorial client to test my webservice. It works fine! However, i tried to compile the client code separately and it didn't worked. The jvm can't find the webservice class. So, the questions are:
    - How to implement an independent static stub whithout the ant help?
    - How can the client get the endpoint to create the proxy?
    - Must I use any javax.xml.rpc interface (call or service maybe) to do the job?
    - Could anybody show me some sample code?
    Well, that's it. I'm waiting for some answer. Please, help me.
    Tks in advance,
    Rodrigo.

    Can you explain what you mean by "independent static stub" ?
    JWSDP Tutorial explains all the steps required to create a static stubs client and invoke the service. In addition, https://jax-rpc.dev.java.net/whitepaper/1.1/index-part2.html#Scenario2 explains the detailed steps to achieve the same from command line.
    Hope that helps.
    Post your JAX-RPC related questions to [email protected] for a quicker resolution.
    Send an email to [email protected] to subscribe to the alias.
    Send an mail to [email protected] for a complete list of help commands.
    -Arun

  • I am getting CONNECTION TIMEOUT error in my macbook(10.7.4).plzzz help me

    i am getting CONNECTION TIMEOUT error in my macbook(10.7.4).plzzz help me

    Thank you very much, i guess it will be the remote servers.
    Then i got this critical error on my local server
    Automatic mail message send from usa12 for SID USA on Fri Dec 15 15:00:01 EST 2006
    DONOT REPLY FOR THIS MESSAGE.....
    Please check the follwing files ( will exist if there was an error )
    /u01/app/oracle/admin/usa/bdump/alert_usa.log.121506.1500 ......
    /u01/app/oracle/product/8.1.7/network/log/listener.log.121506.1500 .....
    ORA-00600: internal error code, arguments: [17182], [27793076],
    I know i need to contact oracle , when i went to Metalink ,i needed to run their RDA it is like diagnostic report script and include it before u send to them.
    I needed some permissions from my Senior so i will do it on monday.
    do you have any suggestions????

  • OCA material needed plzzz help me

    HI
    I want to get OCA certification and i needed OCA material. Anybody help me in this regards?

    AhmedDBA wrote:
    Hi kamran,
    I am asking 10g OCA material for DBA track. could u plzzz help me to get this material downloads in pdf formats and practice tests.
    thanks
    regards AhmedYour response and claim to be a DBA indicates a high (but not absolute) probability you are (or intend to be) a dishonourable cheat and to use breach of copyright material and unauthorized learning methods.
    If you followed the links previously given you would have obtained information on authorized practice tests.
    Location of all the required PDF's for 10g are here: [http://www.oracle.com/pls/db102/homepage], as you seem not to have been able to find that!

  • HT201263 i do click to restore the settings on i phone 3g but after 5 to 8mins it gives an error saying could not restore settings...now what should i do?? plzzz help..:(

    i do click to restore the settings on i phone 3g but after 5 to 8mins it gives an error saying could not restore settings...now what should i do?? plzzz help..:(

    i have locked my phone and i get the usb symbol with the i tunes sign with an arrow..i tried ro upgrade the software which did not go throught succesfully.. plzzz help me  ...

  • I paid an app from the itunes accedently,,, and i want get the money back !!!! plzzz, help me!

    i paid an app from the itunes accedently,,, and i want get the money back !!!! plzzz, help me!

    Never mind speaking another language, writing in it is awsome.  Mind you even I am making an assumption that English is not your first language which may not be the case.
    To your question, it would depend on why you think you may be entitled to a refund, if the app is totally falsely advertised you may have a chance.  If it is just that you don't actually like it you may have less chance.  Give it a go.

  • ArrayList of objects to array of object, does not work

    Hello,
    I have a short problem in transforming an ArrayList full of User 's to an array full of User 's.
    It seems Java isn't supporting this directly, example code:
    function User[] getUsers()
       ArrayList<User> userArrayList = new ArrayList<User>;
       //fill list with User 's
       User[] users = (User[]) userArrayList.toArray();
       return users;
    }     This code gives a class cast exception, cannot cast Object[] to User[].
    Why is this?
    When you manually iterate the arrayList and cast all objects to the User type in the array it will work, but it is more code + kinda takes out the use for a toArray() function.
    Is there something I am doing wrong or is it just not possible in java?

    If you have a Collection<T> after erasure the type of T is Object. Another reason you can't do it is that you could create arrays of generic types, which is not supported.
    p.s. if the array you pass in as a parameter to toArray is big enough it will be used otherwise a new array of the same runtime type is allocated.

  • Using Primitive Arrays in JPA

    Is it possible to persist and store arrays of primitive types using the Java Persistence API? If so, is there any special annotation that the array requires?

    Don't use ASSOC Arrays. Use SETs.
    Also increase the JTA timeout in Weblogic to like say 600 seconds.

  • Reflection & primitive arrays

    hello,
    I call some methods with reflection.....As you know method.invoke(....) returns an instance of Object......I saw on javadoc that primitive data types are wrapped into their corrispondent object:es int->Integer......My problem is with primitive data types arrays: if I have int[] as return type and I cast Object to Integer[] I receive CastException...I tried to discover instance type with reflection, but nothing useful ( something as "[[I" )
    How to solve it?
    Many thanks.
    Paolo                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    You may find this helpful ... it shows some of the methods that you can use to discover more about the type of an array via reflection.
    import java.lang.reflect.Array;
    public class PrimArrayReflect
        public static void main(String[] argv)
        throws Exception
            int[] a = new int[10];
            System.out.println(a.getClass().toString());
            System.out.println(a.getClass().isArray());
            System.out.println(a.getClass().getComponentType().toString());
            System.out.println(a.getClass().getComponentType().equals(Integer.TYPE));
            Array.setInt(a, 0, 123);
            System.out.println(a[0]);
    }

  • Private static ArrayList within java.util.Arrays

    I was recently reviewing the code in java.util.Arrays (class version 1.45 - Java version 1.4.1). Beginning on line 2289 is a private static class named ArrayList. I'm completely baffled as to why the author created this slimmed-down private class (which would be, incidentally, returned by the Arrays.asList(Object[] a) method) rather than use the public class java.util.ArrayList. Can anyone offer an explanation?
    Thanks,
    John

    from JDK JAVADoc:
    asList
    public static List asList(Object[] a)
    Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable.
    So the private ArrayList extends java.util.ArrayList, and any changes made this list does not affect the internal Object[].... in other words can not be changed.

  • Error while copying all rows into an ArrayList...plzzz help

    Hi all,
    Iam doing a small POC on publishing a Application module as webservices...iam stuck while copying the results of whereclause into an arraylist.. some one please help....below is the code
    public class matrixVOImpl extends ViewObjectImpl {
        /**This is the default constructor (do not remove)
        ArrayList al=new ArrayList();
        public matrixVOImpl() {
    public  ArrayList getCompLevels(String role){
        int x=0;
        int pos=0;
        setWhereClause("matrixEO.ROLE='"+role+"'");
        executeQuery();
        if (!hasNext())
                throw new JboException("unable to find role " +role);
        long i=getEstimatedRowCount();
        for(x=0;x<=i-1;x++){
        Row rw=getRowAtRangeIndex(x);************ //here lies the problem for me********************
    String comp= rw.getAttribute("Competency").toString();
        String lr=rw.getAttribute("LevelRequired").toString();
       al.add(0,comp);
      pos=pos+1;
       al.add(1,lr);
      pos=pos+1;
        return al;
    problem is at  Row rw=getRowAtRangeIndex(x); for loop is not workin here...when i manually put zero,first(),last() in place of x works fine i get the first row ..but if i put 1,2...10 or any number i get a null pointer exception..
    how to get all the rows ...wch can b copied to an arraylist...can someone help pllzz.Edited by: Oraclerr on Apr 10, 2009 12:31 PM

    I think it's because getRowAtRangeIndex depends of what the getRangeSize() value is on the view object before executeQuery is invoked. You can change this value in the properties of the viewobject or programmatically, using setRangeSize. If your range size is one, getRowAtRangeIndex(1) returns null, because the index i zero-based. You should only use range size if you only need to present ex. 10 rows a a time?

Maybe you are looking for

  • Work order that is open but closed in IW46

    Hi PM Gurus, I am trying to process a work order in the error log (IW46) but get the message that the order is closed. I have checked the order and it is not closed (it was just recently opened). It there something that has to be run before the error

  • BIOS update, then will not boot from any drive

    This old laptop, 3000 C200 8922 was acting very clunky when on wireless. Downloaded Bios Version 63ET62WW and flashed it into the bios. Now, even though I can get to the bios screen, and it shows the hard drive, DVD/CD drive, it will NOT boot from ei

  • Replication : error code 402

    I've 3 LDAP servers 5.2. Each have same release All are master replica A have a agreement to C B have a agreement to C So A & B can replicate to C I initialize A -> OK I initialize B -> OK I update A -> OK C got the new data I update B -> NOK I becom

  • Portal

    Hi, Is it possible to implement vendor neutral portal? I need to maintain a weblogic portal. It's totally locked in weblogic since it uses jpf, netui, etc.. what's the best approach to avoid vendor specifics. Thanks

  • MONITOR MADNESS - Is it Leopard ? My graphics card perhaps ? HELP

    Friends, I am going nuts ( no don't answer that one ! ). Recently ( possibly after the 10.5.2 graphics update - I can't exactly recall ) my LG flat screen monitor has started to look like a grainy 60's acid art house experiment !! It is subtle but mo