• java好习惯


    1.文件组成的list

    public List<File> getFileList(){
      List<File> list=new ArrayList<File>();
      for (Iterator it=iterator(); it.hasNext(); ) {
        FileResource resource=(FileResource)it.next();
        File file=resource.getFile();
        list.add(file);
      }
      return list;
    }

    2.循环取到最大值

    三元运算符用,奇怪的起始

    public ArrayList<SkinArea> createNotExistingAreas(){
      List<SkinArea> currentZones=this.loadZones();
      ZoneXZ thisZone;
      int maxRow=Integer.MIN_VALUE;
      for (  SkinArea thisArea : currentZones) { 
        if (thisZone.getZ() > maxRow)     maxRow=thisZone.getZ();
      }
      ArrayList<SkinArea> newSkins=new ArrayList<SkinArea>();
      for (int row=0; row <= maxRow; row++) {
        System.out.println("Extending row in DB: " + row);
        for (int x=-Settings.getSkinsRight() + (row % 2 == 0 ? 0 : 1); x <= Settings.getSkinsLeft(); x++) {
          if (!this.areaExists(x,row)) {
            SkinArea newArea=new SkinArea(x,row,"");
            this.saveZone(newArea);
            newSkins.add(newArea);
          }
        }
      }
      return newSkins;
    }

    3.当某为空就付一个初值

    public void addListener(AnimatorListener listener){
      if (mListeners == null) {
        mListeners=new ArrayList<AnimatorListener>();
      }
      mListeners.add(listener);
    }

    4.浮点是这样计算的,强转成float和数字加f

    public void rescale(int boardDiameter,int size){
      Log.d("rescale","Rescaling the board");
      boardRect=new RectF(boardDiameter / 4f - 1,1,3f * boardDiameter / 4f + 1,boardDiameter / 2);
      balls=new ArrayList<RenderBall>();
      ballSize=((float)size - 2 * borderSize) / 9f;
      view.postInvalidate();
    }

    5.如果某个为空加工一部分,如果某个为空加工一部分,生产线的加工模式

    public void addWord(Word word){
      if (word == null)   return;
      String w=word.getWordForm();
      if (w == null)   return;
      String catName=word.getCategory().getName();
      lexicon.addEntry(LexiconEntry.createEntry(word.getEntry()));
      if (categoryMap.get(catName) == null) {
        categoryMap.put(catName,new ArrayList<Word>());
      }
      categoryMap.get(catName).add(word);
      if (textMap.get(w) == null) {
        textMap.put(w,new ArrayList<Word>());
      }
      textMap.get(w).add(word);
    }

    6.浮点型是这么计算的float shift = (5f-i)*ballSize/2f;

    public void updateBoard(Board b){
      this.board=b;
      Log.d("update","BoardDrawer.UpdateBoard at " + System.nanoTime());
      balls=new ArrayList<RenderBall>();
      for (int i=1; i <= 9; i++) {
        float shift=(5f - i) * ballSize / 2f;
        float x, y;
        for (int j=1; j <= 9; j++) {
          int state=b.getState(i,j);
          if (state != Layout.N) {
            x=borderSize + shift + (j - 1) * ballSize + ballSize / 2f;
            y=(float)(borderSize + (i - 1) * ballSize * SQRT3_2) + ballSize / 2f;
            balls.add(new RenderBall(x,y,state));
          }
        }
      }
      if (animBalls != null) {
        animBalls=null;
      }
      if (emptyBalls != null) {
        emptyBalls=null;
      }
      animation=false;
      view.postInvalidate();
    }

    7.当参数个数小于2的时候打印消息提示出错

    public static void main(String[] args){
      try {
        if (args.length < 2) {
          System.out.println("Arguments not valid : {model, folder}.");
        }
     else {
          URI modelURI=URI.createFileURI(args[0]);
          File folder=new File(args[1]);
          List<String> arguments=new ArrayList<String>();
          Extension generator=new Extension(modelURI,folder,arguments);
          for (int i=2; i < args.length; i++) {
            generator.addPropertiesFile(args[i]);
          }
          generator.doGenerate(new BasicMonitor());
        }
      }
     catch (  IOException e) {
        e.printStackTrace();
      }
    }

    8.如果文件不存在,先生成文件夹:if(!file.exists()){file.mkdirs()}

    public void doGenerate(IProgressMonitor monitor) throws IOException {
      if (!targetFolder.getLocation().toFile().exists()) {
        targetFolder.getLocation().toFile().mkdirs();
      }
      monitor.subTask("Loading...");
      org.eclipse.acceleo.tutorial.extension.main.Extension gen0=new org.eclipse.acceleo.tutorial.extension.main.Extension(modelURI,targetFolder.getLocation().toFile(),arguments);
      monitor.worked(1);
      String generationID=org.eclipse.acceleo.engine.utils.AcceleoLaunchingUtil.computeUIProjectID("org.eclipse.acceleo.tutorial.extension","org.eclipse.acceleo.tutorial.extension.main.Extension",modelURI.toString(),targetFolder.getFullPath().toString(),new ArrayList<String>());
      gen0.setGenerationID(generationID);
      gen0.doGenerate(BasicMonitor.toMonitor(monitor));
    }

    9.先把要删的装到一个list里,然后删掉这个list达到删除多个的目的

    private void applyResult(FeedbackResult result,long seqNo,boolean multiple){
    synchronized (waiting) {
        List<FeedbackHandle> toRemove=new ArrayList<FeedbackHandle>();
        for (    FeedbackHandle handle : waiting) {
          if (handle.ackApplies(seqNo,multiple)) {
            handle.setResult(result);
            toRemove.add(handle);
          }
        }
        waiting.removeAll(toRemove);
      }
    }

    10.学习这么抛出异常

    @Override public void login() throws Exception {
      if (characterEncoding == null) {
        detectCharacterEncoding();
      }
      List<NameValuePair> formParams;
      HttpPost post;
      HttpResponse response;
      TagNode document, hiddenUser;
      try {
        formParams=new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("usuario",username));
        formParams.add(new BasicNameValuePair("clave",password));
        formParams.add(new BasicNameValuePair("accion","login"));
        post=new HttpPost(baseUrl + "/formulario.gov");
        post.addHeader("Referer",baseUrl + "/formulario.gov?accion=ingresa");
        post.setEntity(new UrlEncodedFormEntity(formParams,characterEncoding));
        response=client.execute(post);
        document=cleaner.clean(new InputStreamReader(response.getEntity().getContent(),characterEncoding));
        hiddenUser=document.findElementByAttValue("id","user",true,true);
        if (hiddenUser == null || !hiddenUser.hasAttribute("value") || hiddenUser.getAttributeByName("value").equals("0")) {
          throw new RobotException("Invalid user id field");
        }
        userId=hiddenUser.getAttributeByName("value");
        loggedIn=true;
      }
     catch (  Exception ex) {
        logger.error(ex.getMessage(),ex);
        throw ex;
      }
    }

    11.拼url

    @Override public List<HashMap<QuoteAttribute,String>> executeQuery(List<String> securityList,List<QuoteAttribute> quoteAttributes){
      String tickerList=securityListToString(securityList);
      String attributeList=attributeListToString(quoteAttributes);
      HttpClient httpclient=new DefaultHttpClient();
      String urlString=BASE_URL + "?" + "s="+ tickerList+ "&"+ "f="+ attributeList;
      System.out.println("Query url: " + urlString);
      HttpGet httpGet=new HttpGet(urlString);
      try {
        HttpResponse response=httpclient.execute(httpGet);
        HttpEntity entity=response.getEntity();
        if (entity != null) {
          String stringResponse=EntityUtils.toString(entity);
          return processResponse(stringResponse,quoteAttributes);
        }
      }
     catch (  IOException ex) {
        System.out.println("Error " + ex);
      }
      List<HashMap<QuoteAttribute,String>> result=new ArrayList<>();
      return result;
    }

    12.以HashMap为元素的list,里层小循环把元素放到HashMap中,在外层循环中list.add(Map),返回list

    private List<HashMap<QuoteAttribute,String>> processResponse(String response,List<QuoteAttribute> quoteAttributes){
      List<HashMap<QuoteAttribute,String>> result=new ArrayList<>();
      String[] lines=response.split("
    ");
      for (  String line : lines) {
        String[] items=line.split(ATTRIBUTE_SEPARATOR);
        HashMap<QuoteAttribute,String> lineItem=new HashMap<>();
        int i=0;
        for (    String item : items) {
          lineItem.put(quoteAttributes.get(i++),item);
        }
        result.add(lineItem);
      }
      return result;
    }

    13.ServletRequest可以强转成HttpServletRequest

    public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest httpRequest=(HttpServletRequest)request;
      String requestURI=httpRequest.getRequestURI();
      if (requestURI.contains(".nocache.")) {
        Date now=new Date();
        HttpServletResponse httpResponse=(HttpServletResponse)response;
        httpResponse.setDateHeader("Date",now.getTime());
        httpResponse.setDateHeader("Expires",now.getTime() - 86400000L);
        httpResponse.setHeader("Pragma","no-cache");
        httpResponse.setHeader("Cache-control","no-cache, no-store, must-revalidate");
      }
      filterChain.doFilter(request,response);
    }

    14.

  • 相关阅读:
    Documentum之基础(1)
    tomcat部署项目,war包问题[转]
    AD与LDAP区别
    Microsoft Visual Studio2010--此时无足够的可用内存,无法满足操作的预期要求,可能是由于虚拟地址空间碎片造成的。请稍后重试。
    Oracle 11g服务器安装详细步骤
    Oracle 11g 密码永不过期设置
    oracle 11g dbf数据文件从C盘迁移到D盘
    Swift 简介
    0Day 密码重置dede阿帕奇强制安装
    PS抠图教程_抠图小技巧_常用抠图小技巧_图片结构与配色
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5760699.html
Copyright © 2020-2023  润新知