Finding the class of objects in a Collection

Is there a fast way to determine if all of the Objects contained in a Collection are of a specific class ?
For example I may want to verify that all of the Objects in an ArrayList are Strings. Do I have to iterate over the entire list and do an "instanceof String" on each element, or is there a shortcut method ?
Thanks.
--James                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Is there a fast way to determine if all of the
Objects contained in a Collection are of a specific
class ?
For example I may want to verify that all of the
Objects in an ArrayList are Strings. Do I have to
iterate over the entire list and do an "instanceof
String" on each element, or is there a shortcut
method ?If you need to even make this kind of check, there's probably something wrong with your design.
If you're using <= 1.4.x, then, yes, you just have to iterate over the list and check each element.
If you're using >= 1.5, then you can use generics to make it a List<String> or something like that, which will ensure at compile time that nothing but Strings are ever put into the list.

Similar Messages

  • Is there a way to find the class objects memory size?

    Hi Friends,
    Please help.
    Is there a way to find the number of Objects created and total size?
    For example:
    class AgeRecord
    int start;
    int end;
    AgeRecord(int start, int end)
    this.start = start;
    this.end = end;
    In a loop if I create 1000 objects, how will I get the total memory size
    Thanks and Regards
    JG

    You might find this useful...
    package forums;
    http://weblogs.java.net/blog/dwalend/archive/2007/11/the_thing_about.html
    http://forums.sun.com/thread.jspa?threadID=457279&start=30&tstart=0
    http://www.velocityreviews.com/forums/t364574-size-of-boolean-type.html
    The JLS doesn't specify the size of a boolean, leaving it upto the JVM
    implementor to define. Sun's JVM stores booleans as:
    (1) a boolean is-an int; i.e. a signed 32 bit twos-compliment integer.
        At face value, this is an innordinate waste of space, but Java uses a
        32-bit stack frame, and most (modern) CPU's use a 32-bit word anyway,
        so the wasted space is worth the CPU cycles, and it's simple.
    (2) a boolean[] is-a byte array, using 1 byte per element, rounded up to the
        nearest 8, plus 8 bytes for the array-object itself.
        For example: boolean[] bools = boolean[100];
        100 mod 8 = 4; so that'd be 104 bytes + 8 bytes = 112 bytes.
        So, let's dis/prove the contention by experiment.
        1,000,000 mod 8 = 0 so 1,000,000 + 8 bytes for the array = 1,000,008
    class BooleanArraySizeTest
      public static void main(String[] args) {
        final Runtime rt = Runtime.getRuntime();
        System.out.println("The contention is that each iteration should use 1,000,008 bytes.");
        try {
          long before, after;
          final int TIMES = 32;
          boolean[][] bools = new boolean[TIMES][];
          for (int i=0; i<TIMES; i++) {
            before = rt.totalMemory() - rt.freeMemory();
            int n = 1000*1000-(TIMES/2)+i;
            bools[i] = new boolean[n];
            after = rt.totalMemory() - rt.freeMemory();
            System.out.print(n);
            System.out.print('\t');
            System.out.print(after-before);
            System.out.println();
        } catch (Exception e) {
          e.printStackTrace();
    999984 used=1000000 bytes
    999985 used=1000000 bytes
    999986 used=1000000 bytes
    999987 used=1000000 bytes
    999988 used=1000000 bytes
    999989 used=1000008 bytes
    999990 used=1000008 bytes
    999991 used=1000008 bytes
    999992 used=1000008 bytes
    999993 used=1000008 bytes
    999994 used=1000008 bytes
    999995 used=1000008 bytes
    999996 used=1000008 bytes
    999997 used=1000016 bytes
    999998 used=1000016 bytes
    999999 used=1000016 bytes
    1000000 used=1000016 bytes
    1000001 used=1000016 bytes
    1000002 used=1000016 bytes
    1000003 used=1000016 bytes
    1000004 used=1000016 bytes
    1000005 used=1000024 bytes
    1000006 used=1000024 bytes
    1000007 used=1000024 bytes
    1000008 used=1000024 bytes
    1000009 used=1000024 bytes
    1000010 used=1000024 bytes
    1000011 used=1000024 bytes
    1000012 used=1000024 bytes
    1000013 used=1000032 bytes
    1000014 used=1000032 bytes
    1000015 used=1000032 bytes
    ENVIRONMENT:
      Microsoft Windows [Version 6.0.6000]
      Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
      C:\Users\Administrator>java -version
      java version "1.6.0_12"
      Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
      Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
    */Cheers. Keith.

  • FM/Class to find the class and characterstics for a given material

    Hi All,
    Is there any Class/FM to find the class and characterstics for a given material.I tried some BAPI_OBJCL* BAPI's but lot of the BAPI's need classnum as input parameter. But i need a BAPI or tables or class which can give the class and its characterstic values for a given material.

    Hi Ben
             Try ..
    BAPI_OBJCL_GETCLASSES
    BAPI_OBJCL_CREATE

  • From which table I can find the "Class type" and "Class" of the material?

    From which table I can find the "Class type" and "Class" of the material?
    Thanks in advance for the answers....

    Hi,
    try following table
    KSSK     Material number to class     
    KLAS     Class description     
    KSML     Characteristic name     
    CABN/CABNT     Characteristic name description     
    CAWN/CAWNT     Characteristic name
    [http://www.sap-img.com/materials/classification-view-of-material-master.htm]
    [http://wiki.sdn.sap.com/wiki/display/ERPLO/FrequentlyUsedTables]
    Regards
    kailas Ugale

  • How to find the difference in object definition between two databases

    Hi,
    Can any one suggest me how to find the difference in object definition between two different databases. Is there any tool or by OEM? If so how?
    Regards
    Naveen

    this link may be helpful...
    http://www.dbspecialists.com/scripts.html

  • Find the Class Name in a static method

    Hi All,
    I am trying to find the class name inside the static main method. I want to write one main method that loads an instance of the class. Other folks have suggested tricks with the security manager or creating an Exception to look at the stack trace, but these methods don�t reflect the inheritance. I want SUBCLASSES to be able to run from the command line using the inherited main method.
    public static void main(String args[]){
          JPanel thisJPanel = (JPanel) Class.forName(????).newInstance();
    }Any Ideas

    I want
    SUBCLASSES to be able to run from the command line
    using the inherited main method.Someone pointed this out already but more directly, static methods are not inherited.
    The behavior you desire ca be achieved using the Factory pattern.
    The idea of being able to subclass an application is a little bizarre. Why don't you just do something like this:
    public static void main(String[] args){
        // check that there is at least one parameter 
        JPanel thisJPanel = (JPanel) Class.forName(args[0]).newInstance();
    }

  • Which Table, can I find the class and characteristic assigned to equipment.

    Hi all,
    I have assigned a characteristc to a class.
    And assigned this class to an equipment.
    Now in which table can i find the class assigned to this equipment.
    What is the logic to find the class and characteristic.
    Thanks in advance.
    Piyush

    Hi,
    As per above post, you can find classes. To find characteristics, Give EQUNR value in OBJEK field in AUSP table & get the ATINN value.
    Give ATINN value in ATINN field in CABN table & get ATNAM field value.
    In AUSP table, you can get the values against each characteristics as well.
    Regards,
    Maheswaran.
    Edited by: Maheswaran.K on Apr 19, 2011 9:28 AM

  • Cannot find the class!! - URGENT!!!

    I have an JSP archive and I�m using the Tomcat 4. I did a class named ConnectionBean that connect with a database.
    when i start my JSP, the Apache server show me an error page that say it�s impossible to find the class "ConnectionBean". I tryed to put it in the same directory of the JSP file, but happened the same error.
    I tryed to put it in the directory "apache tomcat 4\lib\" but i have the same error.
    I tryed to put it on the directory "jre\lib\ext\ of my JVM, but i have the same error!
    Please, somebody can help me to do my JSP find this class?
    Thanks for all

    after you compile your class you should put the .class in the WEB-INF/classes/ directory
    lets suppose that you wrote in the top of your class
    package com.mydbconnection
    this means that your class should be in
    WEB-INF/classes/com/mydbconnection/MyClass.class
    in your JSP have been like this
    <jsp:useBean id="DBConn" scope="page" class="com.mydbconnection.MyClass" />
    hope this help enough :)

  • Cannot find the class file

    Hi All,
    Can any one help me regarding the issue?
    Error:
    package com.support.misc.feedback
    I am getting the following error for the above line. But I have created the Hierarchy in folder structure. But still it is throwing the error.
    1. Cannot find the class file for com.sapportals.htmlb.page.DynPage
    2. This compilation unit indirectly references the missing type com.sapportals.htmlb.page.DynPage (typically some required class file is referencing a type outside the class path)     FeedbackBean.java
    Thanks in Advance.
    Message was edited by: Gowsika Kannan

    Hi Gowsika,
    the class needed is located in htmlb.jar which can be found under <irj-root>/WEB-INF/portal/portalapps/com.sap.portal.htmlb/lib
    You need to integrate this jar in your .classpath
    Hope this helps,
    Robert
    PS: Please do not post the same question 3 times

  • Cannot find the class file for com.sap.portal.services.api.connectorgateway

    Hi,
    I was trying the "How to BI JAVA SDK in a Portal iView and get the following error.
    The project was not built since its classpath is incomplete. Cannot find the class file for com.sap.portal.services.api.connectorgateway.IConnectorGatewayService. Fix the classpath and try rebuilding this project.
    I have the following in my portalapp.xml file
    <property name="SharingReference" value="com.sap.portal.ivs.connectorservice"/>
    and i have also added the jar file "com.sap.portal.ivs.connectorservice_api" in the set of lib's
    Has some faced a similar issue? or can someone suggest how I could possibly resolve this.
    Thanks,
    Smitha

    Hi Smitha:
       My webdynpro dc was build failed for "This compilation unit indirectly references the missing type com.sap.engine.services.webservices.espbase.client.dynamic.content.GenericObject (typically some required class file is referencing a type outside the classpath)".
    How should i do?  Thank you!

  • Query to find the class name that has the maximum number of students ?

    I need the query to find the [class Name] which has the most number of students. please look below at the tables
    Students Table                                                                     
    StudentId     StudentName  ClassID                                    
    1                  xxx                   1                                           
    2                  yyy                   1                                           
    3                  zzz                   1  
    4                  fff                    2
    5                   ttt                  2
     Classes Table
     ClassID          ClassNane
     1                    CSHARP
     2                    JSHARP
    The result should be : CSHARP
    since there are 3 students in CSHARP and 2 students in JSHARP class
    Appreciate your help
    Thanks

    Try:
    DECLARE @Classes TABLE (
    ClassID INT identity(1, 1) PRIMARY KEY
    ,ClassName VARCHAR(50)
    INSERT INTO @Classes (ClassName)
    VALUES ('CSharp')
    ,('JSharp')
    DECLARE @Students TABLE (
    StudentID INT identity(1, 1) PRIMARY KEY
    ,StudentName VARCHAR(10)
    ,ClassID INT
    INSERT INTO @Students (
    StudentName
    ,ClassID
    VALUES (
    'xxx'
    ,1
    'yyy'
    ,1
    'zzz'
    ,1
    'fff'
    ,2
    'ttt'
    ,2
    SELECT TOP (1)
    WITH TIES C.ClassName
    FROM @Classes C
    INNER JOIN @Students S ON C.ClassID = S.ClassID
    GROUP BY C.ClassID
    ,C.ClassName
    ORDER BY COUNT(S.StudentID) DESC
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • Need  to find the class type for a material

    Hi all,
    i need to find the class type for the material.
    is there any FM or the table where i have both MATNR and KLART fileds.
    Kindly reply asap.
    Thanks
    Sri

    Hi,
    There can be multiple class types assigned to a material. You can view this in the classification tab in the material master transaction.
    You can pass the MATNR to OBJEK field of KSSK table after using neccessary converison Exit to get KLART(Class Type). It will return you a 3 digit Class type. You can find the description of the class from the class type master table TCLA.
    Hope this helps.
    Edited by: Priyabrata Samanta on Feb 11, 2008 11:43 PM

  • How to find the class name of the  BO

    HI
      How to find out a class for a business object.
    For example for the Business Object FORMABSENC i want to find out the class name.
    iam not able to find out from se24 or swo1.
    Or please suggest me how can i use the method createbapistructure of this businessobject.
    Regards
    vijaya

    Hello Vijay
    When you double-click on "method" AbsenceForm.CreateBapiStructure (transaction SWO1) and switch to tab ABAP you see (on ERP 6.0) that the field Name is empty meaning this BO "method" has not yet been implemented.
    Other methods are implemented by modules of function group SWXA. Checking package SWX you will see that there are no suitable classes around for this object.
    Final remark: Methods of business objects has just a semantic meaning and has nothing to do with object orientation (i.e. classes).
    Regards
      Uwe

  • Find Universe, classes and objects used in each report

    I want to find a list of universes, classes and objects used in each report
    or the other way to find list of reports which use a particular universe. please let know, i could not get much information from activity universe in a proper way.

    Hello Venkataramat,
    plese post in more detail what kind of report you are using Crystal report ? webi ? Deski.
    Please post in the specific forums.
    If you have a Crystal Report I recommend to post this query to the [Crystal Reports Design|SAP Crystal Reports; forum.
    Best regards
    Falk

  • Finding the Class of a JavaCompiler's compiled code

    I'm using the new javax.tools.JavaCompiler to make an equation interpreter, but i'm running across some issues. I've got a test program set up:
    package test;
    import javax.tools.JavaCompiler;
    import javax.tools.JavaFileObject;
    import javax.tools.SimpleJavaFileObject;
    import javax.tools.ToolProvider;
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.Arrays;
    import java.util.Date;
    public final class TestJavaCompiler {
        private static boolean compile(JavaFileObject... source) {
            final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            final JavaCompiler.CompilationTask task = compiler.getTask(
                    null,
                    null,
                    null,
                    null,
                    null,
                    Arrays.asList(source));
            return task.call();
        private static String composeAProgram(String className, String expression) {
            return "package test;\n" +
                    "import java.util.Date;\n" +
                    "public final class " + className + " implements Calculator {\n" +
                    "    public double calc( double a, double b ) {\n" +
                    "        return " + expression + ";\n" +
                    "    }\n\n" +
                    "    public Date whenCompiled() {\n" +
                    "        return new Date(1220247303687L);\n" +
                    "    }\n" +
                    "}\n";
        public static void main(String[] args) throws URISyntaxException,
                IOException,
                ClassNotFoundException,
                IllegalAccessException,
                InstantiationException {
            // compose text of Java program on the fly.
            final String programText =
                    composeAProgram("Hypotenuse", "Math.sqrt( a*a + b*b )");
            System.out.println("PROGRAM TO BE COMPILED");
            System.out.println(programText);
            // compile item
            RAMJavaFileObject ob = new RAMJavaFileObject("Hypotenuse", programText);
            final boolean status = compile(ob);
            System.out.println("status of compile: " + status);
            // Load class and create an instance.
            final Calculator calculator =
                    (Calculator) Class.forName("test.Hypotenuse").newInstance();
            // execute its methods:
            System.out.println("Hypotenuse.calc( 3, 4 ) is : " + calculator.calc(3.0, 4.0));
            System.out.println("compiled on: " + calculator.whenCompiled());
    class RAMJavaFileObject extends SimpleJavaFileObject {
        private final String programText;
        public RAMJavaFileObject(String className, String programText) throws URISyntaxException {
            super(new URI(className + ".java"), Kind.SOURCE);
            this.programText = programText;
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return programText;
    interface Calculator {
        public double calc(double a, double b);
        public Date whenCompiled();
    }largely copied and pasted from [http://mindprod.com/jgloss/javacompiler.html], sorry about the whole "post a whole program!" thing.
    Anyways, the program compiles and runs. The dynamicly generated program compiles, but when I try to retrieve the class through Class.forName("test.Hypotenuse").newInstance(), I get an exception "ClassNotFoundException: test.Hypotenuse", and some random stack trace that starts at the forName call. I'm developing this on the NetBeans IDE, so I originally thought that the problem might be that I need to specify the parent folders NetBeans generates ("build\classes\"), but changing the forName to "build.classes.test.Hypotenuse" didn't help. Can anyone give me a reason why this isn't working? I'm pretty much stumped

    Obviously the class isn't loaded. So that suggests one of the following.
    - There is no class output (no byte codes.)
    - It is written as a file.
    - It is written into memory.
    Nothing I saw in the java docs suggests the last. Nothing I can find would suggest the first.
    super(new URI(className + ".java"), Kind.SOURCE);The URI must mean something in the above. Is there a ".java" file created somewhere? Did you open it?

Maybe you are looking for

  • Why does my current balance no longer show up on my prepaid phone?

    I just switched from a Samsung flip phone to the LG Cosmos.  Now the balance will not update on the home screen.  When I called into Verizon they tell me that they do not offer that feature anymore.  I find this hard to believe as it was working fine

  • Will Apple make a 30-pin to lightning connector that will work with a case?

    Why did Apple make the 30-pin to lightning connector useless when you have a case on your iPhone 5/5s? The lightning connector part isn't long enough to fit inside when using Apple's own cases (i.e. the new leather cases for the 5s). Does anyone know

  • Creating a CTabCtrl in a CFormView

    hello, I am trying to create a tab ctrl using CTabCtrl in a CFormView view. I am not able to create the tab control properly. I dont see the tab ctrl getting created. Only one of the child window appears on the view.  I don't see any assertion errors

  • Can't move email into folders

    I archive my sent emails into dedicated folders in one year increments. That is, I have a dedicated folder for email I sent in 2011, another one for 2010 and so on. This week I tried to move some sent emails into a folder dedicated to 2009 and prior.

  • Renumbering a list in Pages 5.5

    In Pages 5.5 I have selected an alinea to be numbered. However my list needs to start with #10 and not #1. In the old Pages this was possible, but now? Anybody?