AsList(java.lang.Object[]) in java.util.Arrays cannot be applied to (int[])

hi all,
i'm getting the above error msg when trying to compile a simple array prog...
while at it, is there another simple way to print the contents
of an array to the console in a single statement except using the asList method??? .. like :
int[] myArray = {1,2,3,4};
System.out.println(myArray);
==================================
here's the code for my program :-
tks in advance.
import java.util.*;
public class ListArray {
public static void main(String args[]) {
     int[] anArray = {2,7,5,8,3};
     for (int i = 0; i < anArray.length; i++) {
     System.out.println("Element No : " + (i+1) + " = " + anArray);
     System.out.println("All the Elements : " + Arrays.asList(anArray));

Funnily enough, thats because int[] is not an array of Objects.
You can make your listing method work by writing this instead:
for (int index = 0; index < anArray.length; index++) {
  System.out.println("Element No: " + (index + 1) + " = " + anArray[index]);
}

Similar Messages

  • Java.util.Array

    Exception in thread "main" java.lang.ClassCastException: Card
    at java.util.Arrays.mergeSort(Arrays.java:1044)
    at java.util.Arrays.sort(Arrays.java:997)
    at CardPlayer.sortHand(CardPlayer.java:91)
    at Game.main(Game.java:75)
    i get this error message after I call a sort method using the java.util.Array
    does anyone know why, or do u need more code?
    thanks

    The Card object needs to implement the Comparable interface if an array of them is to be sorted. The ClassCastException occurs when the sorting code attempts to assign a Card Object to a Comparable variable. The API documentation refers to this problem like this:
    Throws:
    ClassCastException - if the array contains elements that are not mutually comparable (for example, strings and integers).

  • 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.

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • Using java.util.Arrays.binarySearch

    Hi,
    I tried the following code
    import java.util.Arrays ;
    class SecondTry {   
    public static void main(java.lang.String args[]) {
    int xyz[] = new int[10];
    xyz[0] = 5;
    xyz[1] = 6;
    xyz[2] = 1;
    Arrays.sort(xyz);
    System.out.println(Arrays.binarySearch(xyz,5));
    i expected to see a result of 1. But i get a 8.
    I am sure i must be doing something wrong. But not able to figure out what exactly is wrong. Could somebody help?
    TIA,
    Babu

    hi there,
    .The output was 8 because u have declared the array size to be 10,so the values which are not assigned would be assigned to zero,so if you change the array size to 3,u would get the desired output :)
    cheers
    class SecondTry {
    public static void main(java.lang.String args[]) {
    int xyz[] = new int[3]; //change to three
    xyz[0] = 5;
    xyz[1] = 6;
    xyz[2] = 1;
    Arrays.sort(xyz);
    System.out.println(Arrays.binarySearch(xyz,5));

  • Trouble extending java.util.Arrays

    I have written some utility functions for dealing with arrays and I would like to bundle them into a class along with java's built-in array functions (java.util.Arrays). To do this, I tried to extends the class java.util.Arrays like this:
    public class ArrayUtils extends java.util.Arrays
    /* some static methods */
    When I try to compile this with javac (even with no class body between the braces), I get an error "error:Cannot find constructor "Arrays" with matching parameters [JLS 15.12]". Does anyone know what's going on here? Why is the compiler looking for a constructor? And why can't it find one? I would very much appreciate your insight. Thanks. Eli

    Does anyone know what's
    going on here? Why is the compiler looking for a
    constructor? And why can't it find one?Conceputually....
    Inheritance exists to allow one to inherit from an object. In java objects can be created by using a class. However classes in java do not have to be objects. And you are trying to inherit from something that is not an object.
    One of the other uses for class in java is to group a number of convienent functions together. (Grouped functions do NOT represent a class.) That is what java.util.Arrays is.
    Technically....
    The class java.util.Arrays has a private constructor which means you can't derive anything from it.

  • How to set property "java.util.Arrays.useLegacyMergeSort" in jnlp-file?

    Hi,
    I have a problem in a web start application with java 7 and the new sort behavior (exception: comparison method violates its general contract).
    So I like to go back to previous behavior and tried to put the new java 7 system property "java.util.Arrays.useLegacyMergeSort" in the generated jnlp-File:
    <property name="java.util.Arrays.useLegacyMergeSort" value="true"/>.
    Now I can read the property value in java code with System.getProperty("java.util.Arrays.useLegacyMergeSort"), and guess the property was successful set, but the exception still appears?!
    The system property works with command line "javaws -J-Djava.util.Arrays.useLegacyMergeSort=true file.jnlp", but not via doubleclick on the jnlp-file or url and browser.
    Any ideas?
    Cheers,
    Dan

    Only "trusted" set of properties can be set in the JNLP file by unsigned applications.
    List of properties is revised from time to time but it usually takes time for new properties to be added to it (if there is strong demand for it as every property should undergo security audit).
    You can specify arbitrary property if you sign your application and JNLP file.

  • Java 7 update 51 cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints

    Since I installed Java 7 update 51 accessing the EMC VNX Unisphere Console cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints.
    I rolled back to Apple Java 1.6 -005 now I am getting the following error: plug-in failure.
    I think this is cused by the fact that the EMC console application has been written for java 7 and not java 6. Has anybody faced and solved the "java.util.HashMap cannot be cast to java.awt.RenderingHints." error ?

    Hi Yaakov,
    The error is thrown from the  eclipselink.jar:2.5.1 which is a JPA provider .
    Is the above jar bundled in the Oracle Product you are working upon or was this downloaded from external site ?
    If the jar is bundled with the Oracle Product, go ahead a log a SR with Oracle Support with Toplink product group to drill down on the issue, as the issue is happening internally or thrown by the Eclipselink implementation and we've no control....
    Hope it helps!!
    Thanks,
    Vijaya

  • Java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm

    Hi!
    anybody could help me?
    i am getting java.util.HashMap cannot be cast to org.apache.struts.action.ActionForm error when I run my jsp...
    heres my code :
    CommentAction.java
    package com.provintl.rmis.actions;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.sql.DataSource;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import com.provintl.rmis.forms.CommentForm;
    public class CommentAction extends Action {
         Statement stmt = null;
         Connection con = null;
         javax.sql.DataSource dataSource;
         PreparedStatement ps = null;
         ResultSet rs=null;
         byte updFlg = 0;
         Map commentlist = new HashMap();
         /* (non-Javadoc)
         * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
         @Override
         public ActionForward execute(ActionMapping mapping, ActionForm form,
                   HttpServletRequest request, HttpServletResponse response)
         throws Exception {
              CommentForm commentForm = new CommentForm();
              Date date = commentForm.getDaterecord();
              String comment = commentForm.getComment();
              //TODO : temporary 1 == rose
              int userID =1;
              int appID =1;
              String SelectQry = "SELECT "+
                                       "APPLICANT_TBL.CHFNAME, "+
                                       "APPLICANT_TBL.CHLNAME, "+
                                       "APPLICANT_TBL.INTAPPID, "+
                                       "USERHST_TBL.CHCOMMENT, "+
                                       "USERHST_TBL.DTDATECREATED, "+
                                       " USERHST_TBL.INTHSTID "+
                                       "FROM "+
                                       "APPLICANT_TBL "+
                                       "INNER JOIN USERHST_TBL ON (APPLICANT_TBL.INTAPPID = USERHST_TBL.INTAPPID) " +
                                       "WHERE APPLICANT_TBL.CHFNAME ='"+request.getParameter("first")+"' " +
                                                 "AND APPLICANT_TBL.CHLNAME ='"+request.getParameter("last")+"'";
              try {
                   dataSource = (DataSource)getDataSource(request, "RMIS");
                   con = dataSource.getConnection();
                   con.setAutoCommit(false);
                   stmt = con.createStatement();
                   System.out.println("database connected");
                   rs = stmt.executeQuery(SelectQry);
                   System.out.println("database connected");
                   int ctr = 1;
                   while(rs.next()){
                        commentlist.put(ctr,new CommentForm(rs.getString("CHFNAME"),rs.getDate("DTDATECREATED")));
                        ctr++;
                   if(updFlg !=0){
                        String insQry = "INSERT INTO RECRUIT.USERHST_TBL (CHCOMMENT, INTUSERID, INTAPPID)" +
                        "VALUES ('"+comment+"',"+userID+","+appID+")";
                        stmt.executeUpdate(insQry);
                        con.commit();
                        updFlg = 0;
                   HttpSession session = request.getSession();
                   session.setAttribute("commentlist", commentlist);
                   //con.setAutoCommit(true);
              } catch (SQLException se) {
                   System.out.println("We got an exception while preparing a statement:" +
                   "Probably bad SQL.");
                   System.out.println(SelectQry);
                   se.printStackTrace();
                   //System.exit(1);
              finally {
                   try {
                        rs.close();
                        stmt.close();
                        con.close();
                   } catch (SQLException e) {
                        e.printStackTrace();
              return mapping.findForward("comment");
    commentform.jsp
    =============
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-html"     prefix="html"%>
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
    <%@ taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <script>
    function putLabel(lbl, formName){
    if (opener && !opener.closed){
    opener.document.addapp.jobposition.value=lbl;
    window.close();
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>List of open positions</title>
    </head>
    <body>
    <h2>Job Positions Available</h2>
    <%
    int ctr = 1; %>
    <logic:iterate id="myString" name="commentlist" scope="session">
    <table width="100%" border="0">
    <%
    String bakcolor;
    if((ctr % 2) == 0){
         bakcolor = "WHITE";
         ctr++;
    else{
         bakcolor = "SILVER";
         ctr++;
    %>
    <tr><td bgcolor="<%= bakcolor %>">
    <bean:write name="myString" property="value" />
    </td></tr>
    ${commentlist}
    </table>
    </logic:iterate>
    </body>
    </html>
    thank you in advance!

    Shilnag wrote:
    Hello guys,
    I am new to java... I am trying to develop a web application using
    1.Struts1.2
    2.tomcat 5.5
    3.eclipse 3.2.2Big mistake. Nobody new to Java should jump straight into webapps, let alone using a framework like Struts. Debatably, even Eclipse should be left alone.
    It's precisely because of this that you're having problems. Presumably you're following a tutorial or something, but - as demonstrated - as soon as it goes wrong, you're stuck. Learn some core Java first, trust me

  • Error: java.lang.ClassCastException: java.util.Arrays$ArrayList

    Hi,
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj;
    Please help how to solve this problem.
    Thanks,
    cmbl

    cmbl wrote:
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj; Don't do this cast.
    Why are you doing this cast anyway? I think you need to show a small bit of compilable code (or almost compilable except perhaps for this error) and some more explanation.

  • Java.util.Arrays; (method sort( ) )

    1) How to change a direction of sorting (on increase / on decrease)?
    2) Whether exists in java 2 something similar for sorting Strings ?

    1) How to change a direction of sorting (on increase
    / on decrease)?[url http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder()]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder()
    2) Whether exists in java 2 something similar for
    sorting Strings ?Arrays.sort and Collections.sort will both sort the array or list as long as the type implements Comparable (or you supply a separate Comparator). Since String implements Comparable, those sort methods will sort the array or list of strings.
    Making Java Objects Comparable
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html

  • Import java.util.Formatter - cannot resolve symbol

    I use j2sdk1.4.2_04
    when I try to compile my program using Formatter, it response error "cannot resolve symbol"
    Pls help!

    Where did you get this java.util.Formatter from? If you check the official 1.4.2 API for Java, that class does not exisit! However, java.util.logging.Formatter, does exisit...
    http://java.sun.com/j2se/1.4.2/docs/api/
    If you ment: java.util.logging.Formatter have you checked the API to make sure you are using it correctly???
    HTH.

  • Error: java.util.map can not be inherited with different arguments

    Hi,
    I am getting following error while building the source code.
    C:\venus\src\com\martquest\messaging\msgio\MqMessageIOObjectCarrier.java:36: java.util.Map cannot be inherited with different arguments: <> and <java.lang.Object,java.lang.Object>
    [javac] public class MqMessageIOObjectCarrier extends Properties implements IMqMessageIOObjectCarrier
    What should I do to resolve this issue?
    Thanks
    Prachi

    Hi,
    I am getting following error while building the
    source code.whose source code? If it's yours, you'd better look at where you are defining and using Map. The error code tells you exactly what's wrong.

  • Sort(java.util.LinkedList java.lang.Object ) doesn't work

    Why doesn't this work?
    LinkedList<Object> sysPropsKeys = new LinkedList<Object>(System.getProperties().keySet());
    Collections.sort(sysPropsKeys);
    cannot fnd symbol
    symbol : method sort(java.util.LinkedList<java.lang.Object>)
    location: class java.util.Collections

    I will admit to not having Java1.5 installed on my machine. Haven't yet had the chance to play with generics, but the above DOES work in 1.4, and SHOULD work in 1.5
    Maybe I'm naive but, System.getProperties() returns a Properties object right?
    According to the API: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html: Each key and its corresponding value in the property list is a string.
    All the keys SHOULD be strings.
    AFAIK string are comparable, and shouldn't throw class cast exceptions
    Thus the keys returned from getProperties SHOULD be comparable, and compatible for comparision.
    Ok, I can see your point in that some hackers abuse the Properties class by putting non string keys/values into the Properties Map. In that case the code would become more like your above. I'd probably still go with a TreeMap though, rather than a sorted list of keys. Most time you want the keys, you want the values as well. So if the intention is to print out a sorted list of system properties, and their values, keeping it in a map is best.
    Just my 2 cents,
    evnafets

  • I need to retrieve an Object[] of all keys in java.util.Hashtable

    public abstract class ArrayFunctionality {
         * Construct {@link java.lang.Object} array of keys from {@link java.util.Hashtable}
         * @param h {@link java.util.Hashtable}
         * @return array {@link java.lang.String}
         * @throws java.lang.IndexOutOfBoundsException Exception thrown if initial {@link java.lang.Object} array paramater cannot be indexed
        public static Object[] arrayKeys(Hashtable<Object, Object> h) throws IndexOutOfBoundsException {
            Vector<Object> v = new Vector<Object>();
            Enumeration keys = h.keys();
            while (keys.hasMoreElements()) v.add(keys.nextElement());
            return v.toArray();
    // HOWEVER, this occurs with Hashtable<String, String> attrs:
    if (hasSetHashtable) String[] keyArray = ArrayFunctionality.arrayKeys(attrs);
    // DOES NOT COMPILE: ".class expected - not a statement"I am not understanding why this is occurring, please advise, I'm lost on this one.
    Thanx
    Phil

    I still don't understand what you mean but it now
    works..
    I am sorry I just don't understand the difference
    between
    if (hasSetHashtable) {
    String[] keyArray;
    keyArray = ArrayFunctionality.arrayKeys(attrs);
    }AND
    if (hasSetHashtable) {
    String[] keyArray =
    ArrayFunctionality.arrayKeys(attrs);PhilThere is no difference between those two you posted. The difference is between
    String[] keyArray;
    if (...) {
        keyArray = ArrayFunctionality.arrayKeys(attrs);
    }and
    if (...) {
         String[] keyArray;
         keyArray = ArrayFunctionality.arrayKeys(attrs);
    }In the first, the keyArray will exist outside of the scope of the if statement. In the second, the keyArray will no longer exist once you leave the if statement. Which is the same thing jbish said.

Maybe you are looking for

  • Deinterlacing in Compressor

    Does Compressor 2.3 have ANY deinterlacing algorithms that are worth a crap? I'm trying to format some interlaced DV video for the iPod (On another note, we want more options and control in the iPod setting, Apple!), which means deinterlacing. Frame

  • Product category not replicating

    Hi, I have a product categoty in Table T023 in backend system.I am trying to replicate it to SRM. I run R3AS choosing the source system and it run successfully.But when I checked in Comm_Hierarchy I can't find the Product category. what is the proble

  • Text showing up undefined

    i opened a fla that use's actionscript 2 the only way my text will work is if it is static text. thanks, ron

  • Freezes on installing iTunes 9.0.1

    I tried to upgrade my computer from iTunes 8 to 9.0.1 and it froze. I have tried uninstalling both iTunes and QuickTime and then installing again, but without success. It still freezes, right after it downloads the 45MB package. It says "installing"

  • Randomly can't name new folders

    About once a month or so, the finder randomly stops allowing me to name any new folder I create. The folder name will be selected, but nothing happens when I try to type in a new name, and it just stays 'untitled,' even if I click off of it and resel