java好習慣

1.文件組成的listapp

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.循環取到最大值eclipse

三元運算符用,奇怪的起始ide

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.當某爲空就付一個初值post

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.若是某個爲空加工一部分,若是某個爲空加工一部分,生產線的加工模式this

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;url

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的時候打印消息提示出錯spa

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()}code

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達到刪除多個的目的orm

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("\n");
  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.

相關文章
相關標籤/搜索