Only allow the string to the list

Hello

I have an ArrayList.
ArrayList as = new ArrayList();
Now, I want to let only the string to add in this list of tables how can I achieve this? Don't want to use generic.

Please guide.

Ankur Raiyani wrote:
I was asked to do not use generic.

In example you saw generics. It is clearly said if you don't want to use generic drugs, and then use the instanceof keyword.

I want that list allows me only to add the string if I add another object, then it should throw an error.

Exactly, I give an idea how to use instanceof and allow that string in the arraylist objects.

If not clear, please go through the below program:

import java.util.*;
import java.lang.*;
class ArrayListForOnlyString
{

     public static void main(String st[])
     {
          List stringArrayList = new ArrayList(){

               public ArrayList ar = new ArrayList();

               public boolean add(Object ob) throws UnsupportedOperationException
               {
                    if(ob instanceof String)
                    {
                         ar.add(ob);
                         return true;
                    }
                    else
                    throw new UnsupportedOperationException("Only String Object are accepted");
               }

               public void add(int index, Object ob)
               {
                    if(ob instanceof String)
                    {
                         ar.add(index,ob);
                    }
                    else
                    throw new UnsupportedOperationException("Only String Object are accepted");
               }

               public Object[] toArray()
               {
                    return ar.toArray();
               }

               public String toString()
               {
                    return ar.toString();
               }

          };

          try
          {

          stringArrayList.add(new String("10"));
          stringArrayList.add(1,new String("10"));
                // Uncomment the below line and run, it 'll give error , as you are trying to add Integer Object to array list.
          //stringArrayList.add(new Integer("10"));
          System.out.println("The objects of arrayList are : "+stringArrayList);

         }catch(Exception e)
               {
                    e.printStackTrace();
               }
     }

}

Published by: 833545 on August 31, 2011 15:53

Tags: Java

Similar Questions

  • IAM trying to install Adobe In Design CS2 but only allowing the use of 30 days... Do you know how I can get this to run as needed?

    IAM trying to install Adobe In Design CS2 but only allowing the use of 30 days... Do you know how I can get this to run as needed?

    The activation servers have been closed several years ago. See Adobe - CS2 downloads

  • HP Simple Pass only allows the connection to Web site but works

    Simple passage no longer works to log on to the Web site.  The program itself works and when I slide it opens upward new Web sites in another window, but is no longer prompting me or allow me to use it to connect to Web sites.  This started when I reset my settings of IE9 (which I did because all of a sudden, I couldn't open new tab or new websites).  Internet options reset fixed the problem of navigation, but then I could no longer use simple past.  I did a system restore, which fixed the issue simple pass, but then reinstated in the navigation of the show, so I undid the restoration.  There must be a setting on internet options that is initially simple past to no longer work, but I can't understand it.  Please help because after using simple pass for the last 2 years, I don't remember my password!  Thank you!

    Hmm... I really don't know what the SimplePass old interface looks like - it's been a long time I saw that and now I can't access a machine with something older than SimplePass 5.4.0.620

    The new version you are installing is to install an "overload", in other words, you will not remove anything.  You can install the new version and not the export/backup after the installation.

    After updating to the new Version:

    Export is something you want to do from time to time that you add or update your webcards (Web sites / passwords).

    If you don't like the idea of the hard reset driver (described previously), Dungeon it bothers me for later - the driver Hard Reset works for all kinds of 'weird' tangles: sudden SimplePass strangeness, errors "funny screen" touch touch which cease to operate or act funny, sometimes even webcams (although these can be a little tricky to fix).

    For this operation - the SimplePass upgrade, you can just kick the driver Validity Sensor itself.  Reset of driver is a good idea when installing SimplePass - it "opens", so to speak, the installation of the software is more likely to go well.

    Reinstall the existing validity sensor driver:

    Open Control Panel > Device Manager > open biometric devices >

    Right click on your validity sensor driver > Uninstall ( NOT delete)

    Reboot the laptop in a way the pilot can relocate that you connect to

    Then,.

    Download this new package SimplePass and double-click it to install just above your current version - that is to say, do not remove your software SimplePass existing, just load this version on top of what you have now.

    sp59664 HP SimplePass V6.0.100.257 Win7-8

    After you have upgraded to the latest version of SimplePass, you will be able to see the settings, Options, and '? '. Help sections in 'Splash', i.e. SimplePass when you open it.

    In addition to the export:

    You can PRINT ON your webcards.  This carries some risk; the question of the use of SimplePass is to preserve the security of your passwords.  However, if you are in danger to forget or lose your password, you can print the list.  Printing will take about 95% of the words of past, or so... true make sure you keep the list printed somewhere safe.

    Start SimplePass > Options (between the parameters 'wheel spikey' and the '? ') > print all web cards

     

    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    See a Post that is useful - or who teaches you something you didn't know?

    Your HP Experts strive to help.

    Click on the star of congratulations!  It's a big 'thanks' for the author.

    Year of the snake 2013

    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

  • Paid for lightroom and photoshop and only allowing the tests to download

    I'm unable to download photoshop and lightroom, I paid the subscription and it will only allow me to download trials. Can help

    Hello

    First of all, disconnect, then back into creative cloud, using adobe id to pay for your subscription.

    https://helpx.Adobe.com/creative-cloud/help/sign-in-out-activate-apps.html

    Then, if you launch any product of CC 2015 and the pop up still shows a trial message window, please check this link for the resolution:

    https://helpx.Adobe.com/manage-account-membership/CC-reverts-to-trial.html

    Hope this helps!

  • Recent bookmarks do not allow the list of bookmarks.

    When I click on the star and bookmark a page, I expect it to appear on my list of bookmarks, next time I click on the icon of the list. It's not, but if I mouseover "recent bookmarks", he is on this list. How do I get it on my main bookmark list?

    • "Most Visited" and "Recently set bookmark" and "Recent Tags" are examples of what is called Smart Bookmarks folders and are not the real existing folders.
    • These smart folders show a list created by a query of the places.sqlite database that stores the history and bookmarks in Firefox.
    • Bookmarks or history items that appear in a list of smart folder are also stored in another file, and any changes are applied to the element of bookmark or true story.
    • By clicking on the star in the toolbar navigation go to bookmark the page in the "Unsorted Bookmarks" folder and the star lights in blue to show that
    • 'Bookmark this Page' (Ctrl + D) going to bookmark the page in the folder of bookmarks Menu (you will need to confirm that)
    • 'Bookmark this Page' is accessible via the menu shortcut in the area via the menu of bookmarks in Firefox menu button menu or navigation drop-down, or if you use the keyboard via the bookmarks menu (Alt + B)
  • When I change username it locks the computer and only allows the user who tried to change accounts reconnect?

    I log into my account and then I try to change user... when I do that it goes to the windows screen and says that the computer has been locked by the user only the user or an administrator can unlock the computer. I can connect at that time here only return with this user or log in with an administrator account in which the current user is disconnected and then the new user is connected, but not until the current user is totally connected to the wide.

    Hi Loskee,

    The issue of Windows XP, you have posted is better suited for the IT Pro TechNet public. Please ask your question in the TechNet forums for assistance.

    Hope the helps of information.

  • Try to pass the audio to headset mode. Seems to only allow the speakerphone mode.

    In windows xp, I could choose headphones or speakers in the audio settings.

    This has greatly improved the sound when listening with headphones. It makes the sound more "centered" If you wear headphones.

    In windows 7, the only option that that I seem to have is 'speakers '.

    Anyone know how to recover the headset mode?

    Hi K1DBLITZ,

    To set up Headphone virtualization

    1. Open Audio devices and sound themes by clicking Start , clicking on Control Panel, hardware and sound , and then clicking sound.

    2. click on the tab improvements and then click Headphone Virtualization.

    For more information, see the article mentioned below. This article is for windows vista, but also applies to Windows 7.

    Get high definition sound and music from your computer

    http://Windows.Microsoft.com/en-us/Windows-Vista/get-high-definition-sound-and-music-from-your-computer

    Thanks and regards.

    Thahaseena M
    Microsoft Answers Support Engineer.
    Visit our Microsoft answers feedback Forum and let us know what you think.

  • I only allowed the last update of FireFox on my Mac pc. I cannot view videos now friendly families who are posted on the who's who, Godvine, etc..

    I just gave some kind of update on/to leave needing to restart my Mac Firefox. After having done that, I'm not long able to view any video I want to I found Godvine, facebook, youtube, etc. Everything is visible on the screen, however, the play button is not visible. How can I cancel my last update or fix the problem?
    Frances

    In your troubleshooting information, there is npmnqmp 071102000006, I don't know what it is.
    Please make sure that you can try Fix common audio and video questions and please post back with the results.

  • vSphere only allow the field to be disarmed

    While the resolution of other problems for esxi, I used vSphere to define 'domain' of my installation (host-> Configuration-> DNS and Routing tab).

    Now my performance graphs show not all the data and its been like this for more than an hour.

    If I try to go back in the same screen, I can't white field, as the 'OK' button remains disabled. If I try to enter just a space for the domain (which activates the button), and then he complained his invalid characters

    How can I cancel setting the field?

    Simply define a nem to the "working group", a different domain name. You can't leave it empty!

  • Question of mask - only allowing the mask be moved in an instance

    Hello

    I set up a game, where the user must guess which photo is by moving a small hole/portal.  I used the mask feature to do this and managed to fix the portal to the mouse.  However, I must stop the mouse by dragging the portal when the cursor moves outside the image / instance.  This is so the user can then press buttons to return to the main menu, etc..

    Here's the code I used to fix the portal

    onClipEvent (load) {}

    startDrag ("", true);

    Mouse.hide ();

    }

    Hope that all directions (doubtful!).  Would be great if someone can help me.

    See you soon,.

    John

    There are a few things you could do.  If you are looking for the startDrag function, you will see how it includes additional parameters that you specify for limiting the draggable area for the object.  In addition, using these same limits in a slightly different way, with an onMouseMove event handler, you can set up conditionals that detect when the mouse leaves the area so that you can run the stopDrag() function.

  • How to remove the list of Clipboard Viewer *.clp files

    Windows XP (SP3)

    Use the Clipboard to paste images and texts that are then used for a blog.  Once this is accomplished, the items are deleted from the Clipboard.  However, I find the Clipboard Viewer maintains a list of files *.clp.  How to delete/remove the list?
    Spends hours exploring the Internet to find a solution, but without success.
    Be grateful for suggestions.

    Hello

    This free utility that easily.

    Run the program (requires no installation) files - erase all data from the Clipboard or use CTRL X.

    InsideClipBoard - free - whenever you have something to copy to the Clipboard to paste in another
    application, the copied data is saved in several formats. The main application of Windows Clipboard
    only display the basic Clipboard, like text and bitmaps formats, but only displays the list of all formats
    which are stored in the Clipboard. InsideClipboard is a small utility that displays the binary content of all
    formats that are currently stored in the Clipboard and allow to save the content of specific format
    in a binary file.
    http://www.NirSoft.NET/utils/inside_clipboard.html

    Another useful utility free allowing you to clear the Clipboard.

    ClipBoard Viewer - free - look inside your Windows Clipboard. See what your favorite
    ask, in four different (TXT, BMP, WMF and DIB) data format. This handy tool can also
    Clears the Clipboard. New version 2.0: now go to the Windows system tray! http://www.KarenWare.com/PowerTools/ptclpvue.asp

    I hope this helps and happy holidays!

    Rob Brown - Microsoft MVP<- profile="" -="" windows="" expert="" -="" consumer="" :="" bicycle=""><- mark="" twain="" said="" it="">

  • the list widget with different colors for each item in the list?

    I'll add a widget list to my interactive color wheel:

    * http://r0k.us/graphics/SIHwheel.html

    It is an old applet, first published in 1998 and older than Swing.

    The list contains the names of color 1 567 which he knows the color values. I want the background color to each element to be one of the named color. The forefront color name text will be white or black, chosen for readability to her background. Basically, I'm hoping to accomplish what the name of this color page did with its list widget HTML-form:

    * http://chir.ag/projects/name-that-color/

    I studied the java.awt.list document:

    * http://download.oracle.com/javase/1.4.2/docs/api/java/awt/List.html

    SetBackground() and setForeground() methods are implemented, but they seem to apply only to the list as a whole. As far as I know, it seems there is no access to list items themselves as components. I hope that I am just missing what is obvious.

    -Rich

    What you want to do can be easily implemented on a JList swing, with the help of a custom converter. I would advise therefore to rewrite your applet in the swing, then use a JList. That way you can skip JUnit is studying just to force your applet awt to do something of awt was neither designed for and focus on swing of things GUI. Below is an example of how you can implement your JList:

    import java.awt.*;
    import java.math.BigInteger;
    import java.util.Arrays;
    import java.util.Comparator;
    
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    public class ColorList {
    
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
    
             @Override
             public void run() {
              new ColorList().createGUI();
             }
         });
        }
    
        private void createGUI() {
         String[][] array = getArray();
         // sort the array as you wish
         Arrays.sort(array, new Comparator() {
    
             @Override
             public int compare(String[] o1, String[] o2) {
              return o1[1].compareTo(o2[1]);
             }
    
         });
         // create the JList
         final JList list = new JList(array);
         // set some adequate renderer
         list.setCellRenderer(new DefaultListCellRenderer() {
             private static final long serialVersionUID = 1L;
    
             @Override
             public Component getListCellRendererComponent(JList list,
                  Object value, int index, boolean isSelected,
                  boolean cellHasFocus) {
              DefaultListCellRenderer renderer = (DefaultListCellRenderer) super
                   .getListCellRendererComponent(list, value, index,
                        isSelected, cellHasFocus);
              renderer.setText(((String[]) value)[1]);
              int color = new BigInteger(((String[]) value)[0], 16)
                   .intValue();
              renderer.setBackground(new Color(color));
              renderer.setForeground(new Color(0xFFFFFFFF ^ color));
              return renderer;
             }
         });
         final JLabel demoLabel = new JLabel(
              "Display this text in the selected color", JLabel.CENTER);
         list.addListSelectionListener(new ListSelectionListener() {
    
             @Override
             public void valueChanged(ListSelectionEvent e) {
              String[] selected = (String[]) list.getSelectedValue();
              demoLabel.setForeground(new Color(new BigInteger(selected[0],
                   16).intValue()));
             }
         });
    
         JFrame frame = new JFrame("ColorList");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.add(new JScrollPane(list), BorderLayout.LINE_START);
         frame.add(demoLabel, BorderLayout.CENTER);
         frame.pack();
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
        }
    
        private String[][] getArray() {
         return new String[][] {
    
         { "000000", "Black" },
    
         { "000080", "Navy Blue" },
    
         { "0000C8", "Dark Blue" },
    
         { "0000FF", "Blue" },
    
         { "000741", "Stratos" },
    
         { "00FF00", "Green" },
    
         { "FF0000", "Red" },
    
         { "FFFFF0", "Ivory" },
    
         { "FFFFFF", "White" }
    
         };
    
        }
    
    }
    

    Piet

  • updated to 38.2.0 and now I can't see the messages. I don't see the list of folders in the left pane.

    I only see the list of folders in the left pane, but the messages are not displayed. It receives without problem, I can't see the emails.

    pscolnik,

    You were usng the lightning/calendar addon in time. Are you still using it?

  • I'm doing a script that takes a list of e-mail from a text file and then allow me to select a save as a string. I found some ways to get the path of the file, but I'm in check by pulling the list

    I found some ways to get the path of the file, but I am defeated by pulling the list from that. the function of the path get gives me the path as "Macintosh Users:: Documents: extractedb.txt (myUsername).

    What I can't understand is how to get a dialog box to display a list that represents the content in the text file, I need to change the contents of the text file, I need the box to show me what I chose and I want to save my selection as a single string.
    e '.

    example of extractedb.txt information:

    [email protected]

    [email protected]

    [email protected]

    * has a random number of emails as well *.

    I want this is to pull those emails from the text file and turn them into a list so I can get to be a selection in my dialog box.

    Any help would be great = D

    Assuming you have a text file with your example e-mail addresses, the following AppleScript will read this file in a list (mf_List) and then use this list as input to choose among the list. Because multiple selection is allowed (control button), the output is sent to a list (sel_addr). We check if the Cancel button was pressed by testing for false and if this condition is met, we the script error.  Based on a single or multiple list item content of the list, display accordingly.

    game of mf to ((path to the folder as text) & "mail_list.txt")

    the value mf_List to {}

    the value sel_addr to {}

    the value mf_List to paragraphs of (read file mf)

    the value sel_addr to (choose from the list mf_List with title ¬

    ('Mail list' with multiple selections allowed without empty selection allowed)

    If sel_addr is equal to false then

    Error number-128

    return

    end if

    If length of sel_addr is equal to 1 then

    sel_addr display dialog box as text

    on the other

    the value Point to the text of TID to AppleScript delimiters

    the value Point text in AppleScript return delimiters

    display the dialog box elements of sel_addr in the text

    the value Text of point AppleScript delimiters to TID

    end if

    return

  • My names Contact list for Windows Live "disappeared". My ISP says it still resides in my computer, but only Microsoft can allow retrieving the list. What must I do to get these names?

    My names Contact list for Windows Live "disappeared". My ISP says it still resides in my computer, but only Microsoft can allow retrieving the list. What must I do to get these names?

    Hello

    The question you have posted is related to Windows Live; This is why it would be better suited in the Windows Live community. Please visit the link below to find a community that will provide the best support.

    http://windowslivehelp.com/forums.aspx?ForumID=28aff142-9106-4d74-BE08-9b5d9fc0efea

Maybe you are looking for