Troubled by simple array creation

here is the code :
public class Thing<T> {
     // Ok just wanted to check
     // does not compile (but specs says page 12 : should be unchecked WARNING!)
     //  T[] table = new T[25] ;
     // compiler says unchecked cast to type T !
     T[] table = (T[]) new Object[25] ;
sorry : must be trivial but I do not get why the compiler (1.5.0) balks at new Object[x] ....
is there a way to create an array of T?
is that bad doctor?

Why would you want to do that?
private T[] table = new T[25];
why not? (... though I admit it is not permitted by the spec
so I bow out gracefully -BTW why is this absurd? is the compiler unable to generate appropriate code
at compile time?)
ok main point is about compiler still complaining at new Object[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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... ;-)

  • Automatic array creation

    Hi,
    I am trying to build an array automatically by use of boolean array. I use for loop in the VI but when the boolean array false it assigned "0" into the array. I do not want to assign "0", instead of, I want to pass this step and assign when the boolean array element true. How could I do it?
    Egemen
    Solved!
    Go to Solution.
    Attachments:
    automatic array creation.vi ‏9 KB
    array assign.png ‏26 KB

    Use the Build Array in the TRUE case!
    Also, create an array constant and wire that into the shift register in order to initialize it.
    If you are this lost, you really should go through the LabVIEW 101 tutorials.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Conditional Build Array.png ‏15 KB

  • Simple array of Strings

    Hi, I am new to LabView, however I have programmed in various languages to a moderate level.
    I have attached the vi that I am working on to test a simple array.
    All I want it to do for just now so I can get my head around LabView arrays is simply add the string to the array each time the button is pressed.
    So each time the button is pressed I want to add an new element to the array. So after say 10 presses there should be 10 elements
    Regards,
    jmcall10
    Attachments:
    array-test.vi ‏9 KB

    Some general suggestions:
    Use latch action boolean (right-click..mechanincal action). This way it is true until read by the code, the reverts autoamtically back to false (no need for the local variable).
    Your sequence structure has no purpose. Adding to the array is basically instantaneous, so you can add the delay outside. The execution order does not matter.
    Pachi: Your Current VI has no wait unless you press the button, meaning it spins like crazy, consuming all CPU while doing nothing. The wait should be outside the case.
    Pachi: You need to initalize the shift register, else it remembers the data from previous runs.
    Pachi: It is much less efficient to add to the beginning of the array. I recommend to add the new element to the end.
    Here's a quick draft...
    (personally, I would use an event structure, but this should get you started).
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    AddToArray.png ‏25 KB

  • Simple arrays

    hi,
    I am having difficulties with this very simple array (following). I want to store data through a while loop which is why I tried with a very simple example. And it doesn't work. The data is erased every loop, and i must set the dimension of the array (100 for this example) to get something or my array stays at 0... but I won't know it in my VI.
    Thanks for the help!
    Solved!
    Go to Solution.

    Since you are using Replace array element the element needs to exist prior to rewriting the element.
    Here are two examples in on shot:
    The upper one uses autoindexing, this has the disadvantage that you don't have the data until the loop is finished.
    The lower one uses append array element and feedback notes.
    Ton
    Message Edited by TonP on 06-29-2009 11:24 AM
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!
    Attachments:
    AppendAutoIndex.png ‏3 KB

  • My generic array creation problem.

    I'm getting a "generic array creation" error on lines 6 and 14. I've googled it and I'm still having a hard time. Most things I find on it are pretty complicated and as you can see mine's not, I'm in a beginners course. I'm basically writing a class with methods for dealing with a file of donors.
    Here's my code:
    public class DonorList <dlist>
        //Create empty list
        public DonorList()
            storage = new dlist [MAX];
            count = 0;
        //Capacity as specified
        public DonorList (int cap)
            MAX = cap;
            storage = new dlist [MAX];
            count = 0;
        public boolean isEmpty()
            return count == 0;
        public void clear()
            count = 0;
        //Returns number of elements
        public int size()
            return count;
        //Item at position k, position starts at zero
        public dlist get (int k)
            if (k >= 0 && k < count)
                return storage [k];
            return null;
        // e becomes item at position k
        public dlist set (int k, dlist e)
            dlist old = null;
            if (k > 0 && k < count)
                    old = storage [k];
                    storage [k] = e;
            return false;
        //Returns the position of e or -1 if not found.
        public int indexOf (dlist e)
            int k;
            for (k = 0; k < count; k++)
                if (e.equals(storage[k]))
                    return k;
            return -1;
        //Appends e at the end of the list. Returns false on failure.
        public boolean append (dlist e)
            if (count < MAX)
                storage [count] = e;
                count ++;
                return true;
            return false;
        //Adds e at position k. Returns false on failure.
        public boolean add (int k, dlist e)
            int j;
            if (count == MAX || k < 0 || k > count)
                return false;
            for ( j = count; j > k; j--)
                    storage [j] = storage [j-1];
                    storage [k] = e;
                    count ++;
                    return true;
            return false;
        private int MAX = 100;
        private dlist [] storage;
        private int count;
    }Any help as to why I am getting these errors is very much appreciated. Thanks.

    You cannot create an array of a generic, instead you need to create an array of the class the generic extends (in this case Object)
    You then have to cast the array to the generic type which will give you an unchecked warning which you can turn off with @SuppressWarning("unchecked") on the class.
    Generics and arrays don't always play nicely together and this is one case. ;-)

  • [JS CS3] Trouble with changeGrep() array

    This is strange, or else I'm totally missing something simple:
    My script does a GREP search for a text string in a table, and assigns a paragraph style to the string. Next, for each string that was found, I want to merge the cell that contains the string with the two cells directly to the right of the cell. The line
    var myFound = mySelection.changeGrep();
    does the changing of the text string.
    I understand that changeGrep() returns an array, in this case, of insertion points. When I run the script on a table that contains 5 instances of the string that the Grep search is looking for, myFound returns an array of 5 insertion points like I'd expect. Except that if I pause the script and examine the contents of the array, this is what I get:
    myFound[0].parent.contents displays the correct (first) text string that was changed
    myFound[1].parent.contents isn't correct. It displays the contents of the cell directly to the left of he text string that was changed.
    myFound[2] through myFound[4] are also incorrect.
    Again, this is examining the array before I do anything to the table such as merging cells, etc.
    So, why doesn't the array return the correct insertion points?
    Here is the full script function:
    function myProcessTable(mySelection) {
    // Specify the column width
    mySelection.columns.item(0).width = 68;
    mySelection.columns.item(1).width = 103.5;
    mySelection.columns.item(2).width = 24;
    mySelection.columns.item(3).width = 16;
    mySelection.columns.item(4).width = 16;
    mySelection.columns.item(5).width = 16;
    // Find every occurance of ddd.dd/d in the current table, and apply the Table body, cond, center paragraph style,
    app.findGrepPreferences = NothingEnum.nothing;
    app.changeGrepPreferences = NothingEnum.nothing;
    app.findGrepPreferences.findWhat = "\\d.\\d\\d/\\d";
    app.changeGrepPreferences.appliedParagraphStyle = app.activeDocument.paragraphStyles.itemByID(locateParagraphStyle("Table body, cond, center"));
    var myFound = mySelection.changeGrep();
    alert ("Search is completed. " + myFound.length + " replacement(s) made.")
    // merge the cell with the two cells to the right
    for (i=myFound.length-1; i>=0; i--) { // iterate through each found occurance
    var myCell = myFound[i].parent;
    var myTable = myCell.parent;
    var myRow = myCell.parentRow.index;
    var myColumn = myCell.parentColumn.index;
    myCell.merge(myTable.rows[myRow].cells[myColumn+2]);

    Keith,
    changeGrep()'s arrays can't be used for anything, so that's where your script runs into trouble -- it's nothing to do with tables. To work around that, use findGrep()'s array.Immediately before this line:
    for (i=myFound.length-1; i>=0; i--) { // iterate through each found occurance
    add this one:
    var myFound = mySelection.findGrep();
    Peter

  • SATA trouble? Lost array? read this!

    Firstly thanks to the contributors to the SATA FAQ. Feel free to move/copy this to it if u think it makes sense.
    After my 10th iteration of installing XP pro on the rig below , I have found a nasty bug which made me waste all this time:
    Once you have installed your SATA drive(s) according to the FAQ, there is a very simple way to mess it all up: go to the system administration menu, storage administration and CHANGE THE LETTERS (E,F...)OF YOUR CD/DVD drives.
    While this is "legal", at reboot, the system will lose your SATA !!!!
    Instead of reinstalling, go into BIOS and have it auto-detect all the drives whether CD, DVD or HDD.
    This will recover it.
    I went crazy after losing all sorts of RAID arrays! Hope this helps somebody.

    Dude thank-you for your wonder detailed knowldge, I have descovered that lets say xp 1700 in a ultra 2 can only handle at the most 143fsb mult at 12.
    Given the settings" irq's are a major",part of directing traffic and power? example:
    Sound blaster Live , uses two irq's most common at"Auto" is, irq 10, or 5, and Sound blaster 16 emulation usually takes irq 5,. I have found that the sound card in slot3 works great , but to do this I had to change the Bio's and assign slot 3 irq 7 . and make sure printer port has share irq enabled
    Problems that accure with bad traffic are like this. Start a dedicated server. minimize than start your game?":censored:  no sound what could be wrong"? Shoot another problem Connection problem?. The computer nerd is getting trouble over the ordeal. ANSWER! IRQ can fix the problem, Study the irq and make changes as you go. "what would it be like with no stop signs,,,that is the same as a irq. with the same knowldge this topic brings IRQ need to be clearly understood.
    I can honestly say my system is error free and running like a dream.
    xp 2500 barton 333
    creative sound 5.1gamers.
    512 mb kingston ram 400 mhz
    boadband either onboard.
    MSI 5700 128 mb ddr
    Setting are:
    163 fsb
    mult of 11
    ddr 333
    video memory clock down to 450mhz
    3d clock to 390mhz
    The delta is a smooth running board also I want to mention to the person with crackling sounds, change the irq like I did, that fix the problem and the power is totaly too good to be true.

  • Having trouble printing an array of prime numbers that has been resized

    HI, im having trouble with my printPrimeNumbers() method printing the current state of an array, I can only get it to print the original state it was in. The array is inside of a primeNumbers object. I used checkAndResize to resize that array. my printPrimeNumbers method must be void without a parameter. How could i get my PrintPrimeNumbers method to print out a resized array without modifying the parameter? Any ideas.
    Here is my PrimeNumbers class:
    * Created by IntelliJ IDEA.
    * User: Kevin
    * Date: Mar 4, 2007
    * Time: 1:53:56 AM
    * To change this template use File | Settings | File Templates.
    package primes;
    public class PrimeNumbers {
        private boolean [] sieve;
        public PrimeNumbers(int  upper) {
            initializeSieve(upper);
        public int getNthPrime (int n){
        int prime = 0;
        double num;
        if (n >= sieve.length)
            checkAndResize(n + 1);
        for (int i = 0; i < sieve.length; i++){
            if(sieve)
    prime++;
    if (prime == n)
    return i;
    if (prime < n && i == sieve.length -1)
    checkAndResize(2*sieve.length);
    return -1;
    public int getNumberPrimeNumbers(int n){
    int primes = 0;
    for (int i =0 ; i < sieve.length ; i ++){
    if (n > sieve.length){
    checkAndResize(n);
    if(sieve[i])
    primes++;
    else if (sieve[i])
    primes++;
    return primes;
    public int getSieveSize ()
    return sieve.length;
    public boolean isPrime (int n) {
    if (n > sieve.length){
    checkAndResize(n);
    //initializeSieve(n);
    return sieve[n];
    // prints out the prime numbers inside sieve
    public void printPrimeNumbers() {
    int n = 0;
    boolean first = true;
    System.out.print("[");
    for(int i = 0; i < sieve.length - 1; i++){
    n++;
    if(sieve[i] == true && n != sieve.length - 1) {
    if(first) first = false;
    else System.out.print(" ");
    System.out.print(i);
    System.out.println("]");
    // checks length of sieve with N and then resizes sieve if nessecary.
    private void checkAndResize (int n){
    if ((n + 1) >= sieve.length){
    initializeSieve(2*n);
    private void setMultiples (int k) {
    for (int i = 2*k; i < sieve.length; i += k)
    sieve [i] = false;
    private void initializeSieve (int upper){
    if ( upper < 2)
    sieve = new boolean [2];
    else
    sieve = new boolean [upper + 1];
    sieve[0] = false;
    sieve[1] = false;
    for (int i =2 ; i< sieve.length; i ++ )
    sieve[i] = true;
    int bound = (int) Math.ceil(Math.sqrt(sieve.length));
    for (int i = 2 ; i < bound ; i ++)
    if (sieve[i])
    setMultiples (i);
    private String booleanToString (boolean value)
    if (value)
    return "T";
    else
    return "F";
    public String toString (){
    StringBuffer buf = new StringBuffer("[");
    for (int i = 0; i < sieve.length -1 ; i ++)
    buf.append(booleanToString (sieve[i]) + " " );
    buf.append(booleanToString (sieve[sieve.length -1]) + "]");
    return buf.toString();
    here is the client code
            PrimeNumbers test = new PrimeNumbers(16);
            System.out.println(test);
            System.out.println("There are " + test.getNumberPrimeNumbers(16) +
                    " prime nummbers in the sieve from 1 to 15. \n");
            System.out.println("There are " + test.getNumberPrimeNumbers(26) +
                    "  prime numbers in the resized sieve from 1 to 25.");
            System.out.println("\nThe first 25 prime numbers are:");// makes sense why it doesnt work
            test.printPrimeNumbers();
            System.out.println("\nThe 13th prime number is: " + test.getNthPrime(13));
            System.out.println();
            System.out.println("The number 3001 is prime:  " + test.isPrime(3001));do you see how my methods resized it?
    here is the output:
    [F F T T F T F T F F F T F T F F F]
    There are 6 prime nummbers in the sieve from 1 to 15.
    There are 15 prime numbers in the resized sieve from 1 to 25.
    The first 25 prime numbers are:
    [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47]// this is only the first 15 elements
    The 13th prime number is: 41
    The number 3001 is prime: true
    thanks for taking your time to look at this

    What's the problem?
    You say that there are 15 prime numbers in the range 1-25. Your method printPrimeNumbers() prints the last calculated primes, and that is 15. So the program works.

  • Simple WebService Creation using JDeveloper 11.1 Technology Preview 2

    Hi,
    I like the way JDeveloper simplifies the web service creation using the wizards and allows to test the web services from the IDE itself.
    I have the following issues when I tried the step-by-step tutorial (http://www.oracle.com/technology/obe/obe11jdev/11/ws/ws.html) to build a web service. I greatly appreciate if some one can help me with these issues. This tutorial basically provides how to create a simple hello world kind of web service using JDev. Some of the steps are failing in my case.
    Failure 1) Unable to find the WSDL document
    When I invoke the "Test Web Service" menu item HTTP Analyzer is unable to locate the dynamically generated WSDL. I did try with and with-out proxy settings both the cases it failed. However I can see the WSDL if I go to the given WSDL URL in my web browser. I suspect I am missing some thing in Jdeveloper configuration. So I had to manually save the WSDL from the browser to go to further steps.
    Failure 2) Failure in the Response message
    When I invoke the request message I am getting the following error in the response:
    "The selected message is not a SOAP message". However, if I use the browser to test the web service, it is working fine.
    I greatly appreciate if you can provide me some insight into why JDeveloper is failing in these cases.
    Thanks
    Sunil

    It started working after I restarted the JDeveloper with no proxy settings. Seems to be after changing proxy settings JDev need to be restarted to take the preference changes to be effective in this case.
    Another interesting aspect that I noticed was, when HTTP analyzer is running it dynamically sets the proxy in the preferences settings as localhost with the HTTP analyzer port.
    But anyway now I am able to run and test this webservice within the JDev itself.
    Regards
    Sunil

  • Trouble writing pixel array back to gif file

    Hi everyone. I am in the middle of constructing a steganography api for a final year group project. I have taken out the pixels into an array from a gif file. I am having trouble writing it back to a gif file. Here is my code:
    import javaSteg.stegoLibrary.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import Acme.*;
    import Acme.JPM.Encoders.*;
    public class Gif extends Canvas{
         public void encodeGif(byte[] imageData){
              //create toolkit obarrayPointerect
              Toolkit t = Toolkit.getDefaultToolkit();
              MediaTracker tracker = new MediaTracker(this);
              //decode specified Gif cover
              Image img = t.createImage(imageData);      
              tracker.addImage(img,0);
              try{
                   tracker.waitForAll();
              catch(InterruptedException e){
              System.out.println("Tracker interrupted.");
              //retrive picture from image
              int[] pix = new int[img.getWidth(this) * img.getHeight(this)];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(this), img.getHeight(this), pix, 0, img.getWidth(this));
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              return;
              //put into byte array
              byte[] pixels = new byte[img.getWidth(this) * img.getHeight(this)];     
              for(int arrayPointer=0;arrayPointer<pix.length;arrayPointer++){
                   pixels[arrayPointer] = new Integer(pix[arrayPointer]).byteValue();
              //edit pixels not implemented yet
    //assign edited pixels to an image
              img = t.createImage(pixels);
              // Now encode the image using ACME free GIF encoder (www.acme.com)
              try{
                   FileOutputStream fos = new FileOutputStream("D:\\result.gif");
                   GifEncoder encoder = new GifEncoder(img, fos);
                   encoder.encode();
                   fos.close();
              }catch(IOException e) {
              System.out.println("FATAL IOException "+e);
    From this i get a single pixel in my output gif file. Is there a way of swapping out the edited pixels with the origonal pixels in the image file? or an alternative way to write back the complete file.
    Thanks a lot
    MickyT

    ive managed to solve it. For those who come across this thread and want to know the solution i needed to use MemoryImageSource with the pixels inorder to pass them to the createImage method :o)

  • Simple array comparison not working. Please HELP!

    I have been struggling to solve this problem for a few days now, and I'm slowly losing my mind.
    I am in Adobe Acrobat 10.
    I have a group of button fields called: btn0, btn1, btn2, etc.
    I have a group of text fields called: txt0, txt1, txt2, etc.
    I have a script that takes the value of txt0 and makes it the caption for btn0, and so on.
    I have a script that sets the MouseUp action of btn0 to setFocus to txt0, and so on.
    These scripts work fine.
    I have a script that takes the values of all the txt fields and puts them in an array, and sorts it.
    I have a script that takes the array[0] item and makes it the caption for btn0, and so on (alphabetizing my list of buttons).
    Those scripts work fine.
    I am trying to compare the value of the array[0] item to each of the txt fields to find the match, and then set the MouseUp action of btn0 to setFocus to the matching txt field, and so on (so my alphabetized list points to the correct locations).
    This is where I'm at a loss.
    Here is what I have:
    //specified the txt fields
    var txt0 = this.getField("Z name");
    var txt1 = this.getField("A name");
    //etc.
    //put their values into an array called rxArray
    var rxArray = [txt0.value, txt1.value]; //etc.
    //sorted the array
    rxArray.sort();
    //set the captions equal to the sorted array items
    for (var i = 0; i < 5; i++) {
        var b = ("btn" + i);
        this.getField(b).buttonSetCaption(rxArray[i]); //works fine; alphabetizes the list of buttons
        //below is what goes wrong
        for(var x = 0; x < 5; x++) {
            var r = ("txt" + x);
            if(rxArray[i] == r.value){
                var s = (r + ".setFocus();");
                this.getField(b).setAction("MouseUp", s);
    //end
    Here is what I know:
    The alphabetizing and labeling works fine, but the buttons' MouseUp scripts don't work at all. Nothing happens.
    If I change the following piece of the above script:
            if(rxArray[i] == r.value){
                var s = (r + ".setFocus();");
                this.getField(b).setAction("MouseUp", s);
    To this:
            if(rxArray[i] == txt1.value){
                var s = (r + ".setFocus();");
                this.getField(b).setAction("MouseUp", s);
    Because rxArray[0] does equal the value of txt1 ("A name"), then the MouseUp script for btn0 gets set to:
    txt4.setFocus();
    So I know that, each time the nested loop runs, the if statement is true, and the setFocus script updates. Until the end of the loop, leaving the setFocus as the last item run. So why doesn't my script work? It should only update the setFocus script IF the array item matches the txt field, and should set it to THAT txt field.
    Please please help. I know I'm missing something simple in there somewhere.

    @Try67:
    That's a good question. I was running into some other issues and have revamped my code. Here is what I have in my test file:
    A list of five buttons and a list of five text fields. One additional button that sets the focus to the next empty text field to add a new item, and two additional buttons, one that sorts my list alphabetically, and one that unsorts it.
    with the following field names
    The sort button calls function sortName and the unsort calls function sortNumber (the order of entry).
    Here are those scripts in final form:
    function sortName() {
    //first reset the captions for the buttons to blank
    for (var a = 0; a < 5; a++) {
        var b = ("btn" + a);
        this.getField(b).buttonSetCaption("");
    var txt0 = this.getField("t0");
    var txt1 = this.getField("t1");
    var txt2 = this.getField("t2");
    var txt3 = this.getField("t3");
    var txt4 = this.getField("t4");
    var rxArray = [txt0.value, txt1.value, txt2.value, txt3.value, txt4.value];
    for(var m = rxArray.length - 1; m > -1; m--){
        if(rxArray[m] == ""){
            rxArray.splice(m, 1);
    rxArray.sort();
    var newArray = [txt0, txt1, txt2, txt3, txt4];
    for(var n = newArray.length - 1; n > -1; n--){
        if(newArray[n].value == ""){
            newArray.splice(n, 1);
    for (var i = 0; i < rxArray.length; i++) {
        var b = ("btn" + i);
        this.getField(b).buttonSetCaption(rxArray[i]);
        for (var x = 0; x < newArray.length; x++) {
            if(rxArray[i] == newArray[x].value){
                var s = ("this.getField('" + newArray[x].name + "').setFocus();");
                this.getField(b).setAction("MouseUp", s);
    //end
    function sortNumber() {
    var txt0 = this.getField("t0");
    var txt1 = this.getField("t1");
    var txt2 = this.getField("t2");
    var txt3 = this.getField("t3");
    var txt4 = this.getField("t4");
    var newArray = [txt0, txt1, txt2, txt3, txt4];
    for (var x = 0; x < newArray.length; x++) {
        var b = ("btn" + x);
        this.getField(b).buttonSetCaption(newArray[x].value);
        var s = ("this.getField('" + newArray[x].name + "').setFocus();");
        this.getField(b).setAction("MouseUp", s);
    //end
    As you can see, I've used the array lengths rather than fixed numbers, except when clearing the button values. I use a number there because there is no array to reference and didn't feel like making an array just for that. The number of buttons won't change.
    I've also added in a splice() method to remove the blank entries from my arrays when appropriate (making using the array length even more important).
    The result of the sort is:
    The only quirk I've found in all this is with the Add New button, which calls function addNew, which is:
    function addNew() {
    var txt0 = this.getField("t0");
    var txt1 = this.getField("t1");
    var txt2 = this.getField("t2");
    var txt3 = this.getField("t3");
    var txt4 = this.getField("t4");
    var newArray = [txt0, txt1, txt2, txt3, txt4];
    for (var i =  newArray.length - 1; i > -1 ; i--) {
        if (newArray[i].value == "") {
            newArray[i].setFocus();
    //end
    For this, I would have though that running through the array from start to finish looking for the first empty text field and setting the focus to it would have been correct. But that resulted in the last empty text field being focused. So I reversed the for loop to run finish to start, and the result was that the first empty field was focused. Not sure why that is...

  • Simple array

    Hi. I'm trying arrays as a beginner and keep running into the same problem. The error I keep getting is "class, interface or enum expected". I recently installed the new Java 1.6.0_06....
    I started off with a array of arrays and since that didn't work I tried a very simple one which didn't work either.
    http://mindprod.com/jgloss/compileerrormessages.html has a glossary of error meanings which I tried but didn't work.
    Thanks.
    public class Array1 {
         int[] arr = new int[] {1,2,3,4,5};
         public static void main(String[] args) {
         for (int i : arr) {
              print.out.println(i);
         }

    nevermind
    Edited by: JacobsB on May 21, 2008 4:20 PM

  • Simple sprite creation

    This is some oversimplified code from a more complex file I'm
    writing. I'm getting the same error on my other code. Take a look
    at it for me (if you don't mind)- and tell me the proper way to
    name a sprite (or custom class extending sprite) instance, so I can
    then reference it later. :) thanks!

    quote:
    Originally posted by:
    omnidogg
    You can also use array access with objects, so after your
    creation loop, you can access various properties of dynamically
    created and named objects using the following notation
    for (var i=0; i<5; i++)
    root["test_" + i].x = 10;
    root["test_" + i].y = 10;
    root["test_" + i].visible = true;
    which also lets you go several layers deep easily and is a
    much more straight forward and efficient way of coding.
    Sorry, but that is incorrect. You cannot reference the
    Sprites via their "name" property like that. There is confusion
    over DisplayObject.name and the actual instance name

  • ?Simple - array problems?

    Hey..
    This is a simple question, but I have one number that I want to find in an
    array of numbers. However, every time I close LABVIEW and reopen the
    VI, the array reinitialises to something other than what I originally set
    it to.
    Easy I know, but very confusing...
    Thanks Amie

    Thanks. I figured that one out the long way!!
    Roderic Don wrote:
    >"Kevin B. Kent" wrote>> amie wrote>>> >>> > array of numbers. However,
    every time I close LABVIEW and reopen the>> > VI, the array reinitialises
    to something other than what I originally set>>>> Right click on the array
    and select set current value to default>> then save the VI. It will always
    open with those values.>>>> Kevin Kent>>Make sure you right-click on the
    array INDEX and not one of the array elements>when you do this - it does
    make a difference!>>Rod>-->Roderic Don >Research Associate
    II>University of Delaware>Center for Composite Materials>302-831-8701>302-831-8525
    (FAX)>>

Maybe you are looking for