How an array implements an interface?

Section 5.5 of JLS (dealing with casting conversions) explains something like this:
When an interface type S is cast to an array type T,
"then T must implement S, or a compile-time error occurs. "
I could not understand how an array can be made to implement an interface.
I guessed it means that the component type of array implements the interface, and prepared the following test code. It doesn't compile.
interface S{  }
class C implements S{ }
class Test {
public static void main(String[] args) {
     C[] ac = new C[100];
     S s = new C();
     C[] ac1 = (C[])s; //doesn't compile
     System.out.println(ac1.length);
Would someone open my eyes? Thank you

dmbdmb Your correction compiled my code. But I was not looking for that, because the corrected code casts an array type to array type. Anyway, thanks.
jverdYou are the man. Now I got it. Thank you.
I think I will have to remember your simplified rule (Then S must be Serializable or Cloneable) rather than the JLS' rule. With your rule, I can write a test code like this, which compiles, and which shows that an interface type can be cast to array type.
import java.awt.Point;
import java.io.Serializable;
class Test {
        public static void main(String[] args) {
           Point[] pa = new Point[100]; //any array of reference type
           Serializable s = new String("test");
           Point[] pa1 = (Point[])s; //compiles, though invalid at runtime
}

Similar Messages

  • Set array instance to Interface datatype

    <prelude>This is an odd question with no real significance to me, other than pure interest...</prelude>
    Suppose the following...just for example
    Integer[] arrInteger = new Integer[5];I understand that the following is legal..
    Interface i = arrComp;...provided that the Interface is either Cloneable, or Serializable.
    Why is this legal....Are arrays always serializable as defined in the language spec...
    If arrays are Cloneable, shouldn't they override the method "clone" from the Object class..and how do they do that, there are no classes for arrays....Or maybe they just "do" as a feature of being an array...
    It just seems odd that it is possible to set an array, any array to a Cloneable or Serializable interface.

    I've done what I probably should have done before I posted, I've consulted the Java Language Specification ( http://java.sun.com/docs/books/jls/ )and there I've found my answer..
    From the section Conversion and Promotions....
    Assignment of a value of compile-time reference type S (source) to a variable of compile-time reference type T (target) is checked as follows:
    If S is an array type SC[], that is, any array of components of type SC:
    If T is an interface type, then a compile-time error occurs unless T is
    the type java.io.Serializable or the type Cloneable, the only interfaces implmented by arrays.
    So it looks like arrays implement these interfaces and that is why this assignment is legal. I just didn't realize that.

  • How to implement XI interfaces in online and offline modes?

    Hi Everybody,
    Can you please tell me how to implement XI interfaces in online and offline modes?
    thanks a lot,
    Ramya Shenoy.

    Hi,
    Are you looking for Push and Pull mechanism of PI?
    When the adapters like SOAP, HTTP, IDOC, etc. send the data to PI , it is nothing but a push mechanism, and hence the communication is synchronous by default.
    But adapters like JDBC, File, etc. they fetch the data from Source Applications, so it is a kind of Pull mechanism for PI, and
    by default communication is asynchrnous.
    Pls elaborate exactly what are you looking for?
    Regards,
    Supriya.

  • How to find out in program which all classes have implemented an interface

    Hello,
    I have created an interface and few classes are implementing the interface.
    I want to know in a program which all class have implemented the interface.
    Is it possible to find it out and how?
    Regards,
    Bikash.

    Hi Bikash,
    Read the Database view VSEOIMPLEM with where condition REFCLSNAME = Interface Name and version = 1.
    This would give you all the classes which have implemented the interface and are active...
    If you want to look at the values that the field version can have then see Type Group SEOC ans search for version....
    Hope this help...
    Regards,
    Sitakant

  • How to implement class interfaces

    Hi all,
    We are getting the below error message
    Error message is  Interfacemethod  "IF_EX_LE_SHP_DELIVERY_PROC~SAVE_AND_PUBLISH_BEFORE has not yet been implemented".
    Could somebody tell me how can i implement a class interface.
    Class interface: ZCL_IM_ATP_WM
    Appreicate your help.

    Hi,
    while double clicking on the method IF_EX_LE_SHP_DELIVERY_PROC~SAVE_AND_PUBLISH_
    BEFORE
    Error message is Interfacemethod "IF_EX_LE_SHP_DELIVERY_PROC~SAVE_AND_PUBLISH_BEFORE has not yet been implemented". 
    It is not opening to write my code.
    Any suggestion.
    Thank you
    Mamatha

  • How can I know a class which implements Runnable interface has terminated?

    Hello! I have a class which has implements Runnable interface, while I want to execute some operation when the thread has terminate in multithread enviroment.How can I know the thread has terminated?Does it give out some signal?Cant I just call my operation at the end of the run() method?

    I want to execute some operation when
    the thread has terminate in multithread enviroment....
    Cant I just call my operation at the end
    of the run() method?Sure. Before run() ends, invoke that other operation.
    How
    can I know the thread has terminated?Does it give out
    some signal?Not that I'm aware of, but you can do what you described above, or I believe a different object can call isAlive on the thread.

  • How to implements two interface?

    i have a applet to implement two interface,the actionlistener and the appletcontext.how to do it??
    Thank You!

    with a comma

  • How can my web service class implement an interface

    I am not able to write :
    webserviceclass implements interface
    I am using servicegen script to convert java file to the web service.But then also,if i add
    javaClassComponents="javaclass1,interface1"
    It is saying interface1 does not have any no arg constructor,so can't used in the web service.
    kindly tell how can i code my web service to implement an interface.

    This forum focuses on end-user support. You can find more web development help on the [http://forums.mozillazine.org/viewforum.php?f=25 mozillaZine Web Development board]. Separate forum, separate registration. Please note the tips in the Sticky Post at the top of the forum before posting.
    That said... Firefox honors the setting autocomplete="off" in the form tag. When this attribute is set, users should not be prompted to save the username/password, and it should not be filled automatically. (Is this what wasn't working??)
    https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion
    Knowledgeable users can bypass this setting by running a script to strip this attribute. I doubt that very many users would do that, but if people have to log in very frequently, it is more likely to happen. Users also may use add-ons that manage passwords, and those add-ons might not honor the autcomplete="off" setting. I haven't used any such add-ons, so I don't know the situation there.
    I'm sure this isn't completely satisfactory but hopefully it helps to some extent.

  • How to get classes which implement the interface in program

    Hi,
    I created an interface and some classes are implementing it. I want to know in which classes the interface is implemented through program. I mean in which table the interface implemented details stores.
    please helps regarding this.
    Thanks,
    Regards,
    Priya

    Hi.,
    Read the  database view VSEOIMPLEM with where condition.,  REFCLSNAME =  <Interface Name> and Version = 1.
    This gives the class names which implement the interface.,
    hope this helps u.,
    Thanks & Regards,
    Kiran

  • How to name implementation of an interface

    Hi there
    is there any standard for naming concrete implementation of interfaces?
    So if I have an interface
    A
    in package "interfaces"
    is it sensful to call the concrete implementation of the interface interfaces.A A, too?
    class A implements interfaces.A{
    }? Or should it be called ConcreteA, or or or....?
    Thx for your tips.
    Sincerely
    Karlheinz Toni

    JebeDiAH heres a very interesting reading.
    Class and Interface Names
    Class names are always nouns, not verbs. Avoid making a noun out of a verb, example DividerClass. If you are having difficulty naming a class then perhaps it is a bad class.
    Interface names should always be an adjective (wherever possible) describing the enforced behaviors of the class (noun). Preferably, said adjective should end in "able" following an emerging preference in Java. i.e. Clonable, Versionable, Taggable, etc.
    Class, and interface names begin with an uppercase letter, and shoule not be pluralized unless it is a collection class (see below).
        Acceptable:
            class FoodItem
            interface Digestable
        UnAcceptable:
            class fooditem
            class Crackers
            interface Eat
    Naming collection classes (in the generic sense of collection) can be tricky with respect to pluralization. In general each collection should be identified as a plural item, but not redundantly so. If you are a collection type as part of the class name (List, Map, etc.) it is not necessary to use the plural form in the class name. If you are not using the collection type in the name it is necessary to pluralize the name. If you are extending one of the java colletction class (Map, HashMap, List, ArrayList, Collection, etc.) it is good practice to use the name of the collection type in the class name.    
        Acceptable:
            class FoodItems extends Object
            class FoodItemList extends ArrayList
            class FoodItemMap extends HashMap
        UnAcceptable:
            class FoodItem extends ArrayList
            class FoodItemsList extends ArrayList
    Class names should be descriptive in nature without implying implementation. The internal implementation of an object should be encapsulated and not visible outside the object. Since implementation can change, to imply implementation in the name forces the class name and all references to it to change or else the code can become misleading.
        Acceptable:
            AbstractManagedPanel
            LayeredPanel
        UnAcceptable:
            PanelLayerArray
    When using multiple words in a class name, the words should be concatenated with no separating characters between them. The first letter of each word should be capitalized.
        Acceptable:
            InverntoryItem
        UnAcceptable:
            Inverntory_item
            Inventoryitem
    Other than prefixes, no abbreviations should be used unless it is a well known abbreviation.
        Acceptable:
            CD=Compact Disc
            US=United States
        UnAcceptable:
            Cust=Customer
            DLR=Dealer
    I found it at http://www.iwombat.com/standards/JavaStyleGuide.html

  • How do i implement dynamic feature like arraylist in an array

    how do i implement dynamic feature like arraylist in an array

    funny
    but can u realy give me that code

  • How to implement FCoE interface on OL 6.3

    Hi everybody,
    I try to enable FCoE on a server with Oracle Linux 6.3 but I have some troubles...
    The server is an UCS C240-M3 with an UCS 1225 VIC (Virtual Interface Card). Per default, my Linux has set 6 network interfaces with DHCP (eth0 -> eth5). It corresponds to a 4 Gigabit PCI card + 2 Virtual NIC from the VIC 1225 adapter. The VIC 1225 is supposed to be used for Networking and FCoE, thanks to VLANs.
    Linux displays two FCoE devices with lspci:
    [root@localhost /]# lspci | grep -i fcoe
    0d:00.0 Fibre Channel: Cisco Systems Inc VIC FCoE HBA (rev a2)
    0e:00.0 Fibre Channel: Cisco Systems Inc VIC FCoE HBA (rev a2)
    And it appears that drivers are well installed:
    [root@localhost ~]$ dmesg | grep fnic
    fnic: Cisco FCoE HBA Driver, ver 1.5.0.1
    fnic 0000:0d:00.0: PCI INT A -> GSI 46 (level, low) -> IRQ 46
    fnic 0000:0d:00.0: setting latency timer to 64
    fnic 0000:0d:00.0: irq 75 for MSI/MSI-X
    fnic 0000:0d:00.0: irq 76 for MSI/MSI-X
    fnic 0000:0d:00.0: irq 77 for MSI/MSI-X
    fnic 0000:0d:00.0: irq 78 for MSI/MSI-X
    scsi1 : fnic
    fnic 0000:0e:00.0: PCI INT A -> GSI 40 (level, low) -> IRQ 40
    fnic 0000:0e:00.0: setting latency timer to 64
    fnic 0000:0e:00.0: irq 79 for MSI/MSI-X
    fnic 0000:0e:00.0: irq 80 for MSI/MSI-X
    fnic 0000:0e:00.0: irq 81 for MSI/MSI-X
    fnic 0000:0e:00.0: irq 82 for MSI/MSI-X
    scsi2 : fnic
    How can I enable FCoE on my Linux ? I found some help on the Internet, and examples show how to use ethN interface etc.... I don't know how we habitually identify the interface (eth*) to use with FCoE. Is the FCoE interface considered as a "network" interface by Linux, and generates a script in /etc/sysconfig/network-script ? Am I supposed to see additional interfaces (eth6 and eth7) and use it for FCoE ?
    Thanks

    Ok but in my case, even if the physical Cisco card is a CNA device (it is plugged with a link to the FCoE switch, and a link to the Ethernet network), the Operating System doesn't see such a device since we have configured on the UCS :
    - Two virtual interfaces for Ethernet traffic
    - Two virtual interfaces for FCoE traffic
    Here we have the same behavior as a virtual machine, when it is connected to virtual devices. For the operating system, the two virtual devices configured on UCS side for FCoE are seen as physical dedicated FCoE devices.
    So I don't need to configure an ethX device for both Ethernet and FCoE, because both FCoE and Ethernet traffic are separated.

  • How can I implement This? - Via Multiple Threads

    Hi Friends,
    I m getting a list of 4000 emails in an ArrayList. Now I want to put 300 addresses in a mail at a time, and Want to create a new Thread and Send a Mail.
    I want to run 20 threads at a time to do so, Means Each thread is taking 300 addresses from array assigning it to Message and send it. After Sending it should return to ThreadPool.
    Also the 300 addresses should be removed from arraylist.
    Here are code snippet, i m using..
    MailBean.java - A bean which have all the MailProperty and Send Method.
    MailSender.java - It implements Runnable Interface, In its constructor A MailBean Object is Created and in run method it is sending the Mail.
    FileReader.java - It extends ArrayList, it takes a fileName, parse the Emails add email.
    Main.java - Here i want to send mails using ExecutorService class of java.util.concurrent.
    Mailer.java (Main Class)
    public class Mailer {     
         private final FileReader toEmails;
         private ArrayCollection<String> emails ;
         public Mailer(String addressFile){          
              toEmails = new FileCollection(addressFile);
              emails = new ArrayCollection<String>();
                          Here I want to read the 300 emails from toEmails append it in a String and add it to emails ArrayCollection.
        public static void main(String[] args) {
            try{
                 BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(200);
                 Executor e = new ThreadPoolExecutor(50, 50, 1, TimeUnit.SECONDS, queue);
                    if (args.length != 1) {
                         System.err.println("Usage: java ExecutorExample address_file" );
                         System.exit(1);
                  Mailer mailer = new Mailer(args[0]);
                  MailBean bean = new MailBean();
                  bean.setSubject("Mail Bean Test");
                  bean.setMessage("Hi This is a Test Message, Please Ignore this Message");
               /*  I want to run the send mails to all the emails (300 emails per String.) with the Exceutor.
                   Can somebody tell, I want a new object of MailSender for each mail
                   and sendmails
                 System.out.println("Creating workers");
                 for(int i = 0; i < 20; i++)
                     e.execute(new MailSender(bean));
                 System.out.println("Done creating workers");
            }catch(Exception ex){
                 ex.printStackTrace();
    } Can Somebody give me hint, How can we do it?

    The problem is the sound buffer. You may stop the method which dispatch the notes to be played... but not clear your sound card buffer....
    anyway: you should implement it in daemon threads. This way you can control the thread suspend, stop, restart, etc.
    use Thread.sleep(milliseconds);

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • How I would implement the print mehtod?

    I have this code...
    * SinglyLinkedList.java
    * An implementation of the List interface using a
    * singly linked list.
    * (P) 2000 Laurentiu Cristofor
    * Modified (slightly) for s03 by D. Wortman
    // The class SinglyLinkedList provides an implementation of the List
    // interface using a singly linked list.  This differs from the Java
    // class LinkedList, which employs a doubly linked list and includes
    // additional methods beyond those required by the List interface.
    // Note: Included in this file is (at least) a "stub" method for each of
    // the required methods, as well as an implementation of the Node class.
    // This allows the file to compile without error messages and allows
    // you to implement the "actual" methods incrementally, testing as you go.
    // The List interface include some "optional" methods, some of which are
    // included here (see the List API for the meaning of this).
    // Some of the methods are preceded by comments indicating that you are
    // required to implement the method recursively.  Where there are no
    // such comments, you can provide either an iterative or a recursive
    // implementation, as you prefer.
    // There are some methods that you are asked not to implement at all.
    // Leave these as they are here: they are implemented here to just
    // throw an UnsupportedOperationException when they are called.
    // Hint: Read carefully the comments for the interface List in the
    // online documentation (Java API).  You can also take a look at the
    // implementation of the LinkedList class from the API. It uses a
    // doubly linked list and it is different in many places from what
    // you need to do here. However it may help you figure out how to do
    // some things. You shouldn't copy the code from there, rather you
    // should try to solve the problem by yourself and look into that code
    // only if you get stuck.
    import java.util.*;
    public class SinglyLinkedList implements List
      // an inner class: This is our node class, a singly linked node!
      private class Node
        Object data;
        Node next;
        Node(Object o, Node n)
          data = o;
          next = n;
        Node(Object o)
          this(o, null);
        Node( )
          this(null,null);
      private Node head; // the "dummy" head reference
      private int size;  // the number of items on the list
      public SinglyLinkedList()
        head = new Node(); // dummy header node!
      public void add(int index, Object element)
      public boolean add(Object o)
        return true;
      public boolean addAll(Collection c)
        return true;
      public boolean addAll(int index, Collection c)
        return true;
      public void clear()
      // write a recursive implementation here
      public boolean contains(Object o)
        return true;
      public boolean containsAll(Collection c)
        return true;
      public boolean equals(Object o)
        return true;
      // write a recursive implementation here
      public Object get(int index)
        return null;
      // NOT implemented: we don't cover hash codes
      // and hashing in this course
      public int hashCode()
        throw new UnsupportedOperationException();
      public int indexOf(Object o)
        return -1;
      public boolean isEmpty()
        return true;
      public Iterator iterator()
        return null;
      public int lastIndexOf(Object o)
        return -1;
      // Not implemented: The following two operations are not supported
      // since we are using a singly linked list, which does not allow
      // us to iterate through the elements back and forth easily
      // (going back is the problem)
      public ListIterator listIterator()
        throw new UnsupportedOperationException();
      public ListIterator listIterator(int index)
        throw new UnsupportedOperationException();
      // write a recursive implementation here
      public Object remove(int index)
        return null;
      public boolean remove(Object o)
        return true;
      public boolean removeAll(Collection c)
        return true;
      public boolean retainAll(Collection c)
        return true;
      // write a recursive implementation here
      public Object set(int index, Object element)
        return null;
      public int size()
        return size;
      // NOT implemented: to keep the homework reasonably simple
      public List subList(int fromIndex, int toIndex)
        throw new UnsupportedOperationException();
      public Object[] toArray()
        Object[] array = new Object[size];
        Node n = head;
        for (int i = 0; i < size; i++)
            array[i] = n.data;
            n = n.next;
        return array;
      public Object[] toArray(Object[] a)
           // you'll find this piece of code useful
        // it checks the exact type of the array passed as a parameter
        // in order to create a larger array of the same type.
        if (a.length < size)
          a = (Object[])java.lang.reflect.Array.
         newInstance(a.getClass().getComponentType(), size);
         else if (a.length > size)
          a[size] = null;
        Node n = head;
        for (int i = 0; i < size; i++)
            a[i] = n.data;
            n = n.next;
        return a;
      public static void main(String args[])
           System.out.println("Singly Linked List");
           System.out.println();
           SinglyLinkedList l = new SinglyLinkedList();
           l.add("F");
    }        how should I implement the print method?
    should I use the iterator?
    can someone help me, please.
    Thank You
    Ennio

    actually, you would do the same thing for a toString() method as you would for a print() method. You are just going to return a String instead of using i/o. I would use an iterator to walk over your list of Nodes and then call toString() on each object in your list of Nodes.

Maybe you are looking for

  • OBIEE 11g - Data Fetch Issue.

    Hi, I am facing this weird issue regarding data fetching while executing Reports in OBIEE 11.1.1.5. When I login to the BI user interface and execute any report for the first time, everything is working fine. Bt after that I am not able to execute an

  • ArrayList nested iterators

    How do I clone an Iterator so that I can use a nested iterator over an ArrayList? The problem with the code sample below is the inner iterator (Iter2) advances the outer iterator (iter) so that the outer iterator only examines the first cell in the A

  • No Service iOS 4.0.1

    Greetings all, I am having trouble in getting a signal for my iPhone 3gs. It was bought in Dubai. I had no problems back then when it was on iOS 3.x.x.. Coverage was good then.. I updated it to 4.0.1 and the coverage slowly deteriorates. It was usabl

  • Opendocument link showing parameter while using lsS

    Hi, We are using OpenDocument to view a report. We want to pass the default values to the parameters for crystal report. While using lsS when the date is specified to the parameter the parameter to which the value is assigned stops getting displayed

  • Support pack issues

    Hi All,       After the SP15 was applied many of the data sources became inactive or not in Sync with the source system.       We had to open up the production system, activate the data source and replicate the meta data.       this is also a common